0

Good Evening, This question is an extension for document.getElementById to include href I currently have a next hyperlinks and the next hyperlinks is using a javascript to overwrite the url. The first time I click the next hyperlinks, it works but when the second times I clicked it, it goes to the url which in the a tag but not the javascript. How can I make the next hyperlinks goes to the url which is in the javascript everytime I click it?

<script> 

//..
   function nextHyperLinks() {

          document.getElementById("nextID").href = "www.google.com";
   }
</script>

<HTML>
   //..
   <a href="www.yahoo.com" id="nextID" onclick="nextHyperLinks();">next</a>
</HTML>

If any things not clear, please let me know. Need some hints and advised, thanks.^^

Community
  • 1
  • 1
薛源少
  • 306
  • 1
  • 6
  • 18

2 Answers2

0

Try this:

function nextHyperLinks(e) {
  e.preventDefault();
  document.getElementById("nextID").href = "www.google.com"; // you probably don't need this if you will anyway navigate away from the page.
  window.open('http://www.google.com/', '_self');
}

var el= document.getElementsById('nextID');
el.addEventListener('click', nextHyperLinks);

and remove the inline onclick="nextHyperLinks();"

Sergio
  • 28,539
  • 11
  • 85
  • 132
  • ya, it works in the pure html web site... may I know why u use the preventDefault? will it works the same way if java servlet involve? – 薛源少 Aug 05 '13 at 06:59
  • @薛源少 the preventDefault is so the link in the a tag will not be followed. – Sergio Aug 05 '13 at 07:02
0

http://jsfiddle.net/45WQq/

<a href="http://www.yahoo.com" id="nextID" onclick="this.href = 'http://www.google.com'" target="_blank">next</a>
GwenM
  • 1,198
  • 10
  • 24