简体   繁体   中英

Javascript get anchor href on click

How can I get the href of an anchor when I click on it using javascript? I did the following:

function myFunc() {
}
window.onclick = myFunc;

But how to extend the function to respond only to clicks on anchors and get the href?

function linkClick(e) {
  alert(e.target.href);
}
links = document.getElementsByTagName('a');
for (i = 0; i < links.length; i++)
  links[i].addEventListener('click', linkClick, false);

Your document.onclick registers the handler on the whole document. But you should add it to every link. You can do this with JavaScript and using a framework like Prototype or jQuery makes it a lot easier:

$$('a').invoke('observe', 'click', function(a){
    myFunc(a);
});

But you can also use pure JS combining the getElementsByTagName function with a loop (see Delan's new answer).

it won't work like this, you need to setup an onclick handler for every anchor. The easiest way to do this, is to use a javascript framework like jQuery or Prototype or something similar.

extend your function to recieve the calling object:

var myFunc = function(target) {
  var href = target.href;
  // ... your function code that can now see the href of the calling anchor
}

jQuery:

$('a').click(function(){
  myFunc(this);
});

Protype: see Kau-Boy 's answer

function myFunc(link) {
  alert(link.href);
  return false; // return false if you don't want to actually navigate to that link
}


<a href onclick="return myFunc(link)">something</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM