Javascript gets href binding on click

How can I get href bindings when I click on it using javascript? I have done the following:

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

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

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

document.onclick . . JavaScript , Prototype jQuery, :

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

JS, getElementsByTagName (. Delan new answer).

+2

, onclick . - javascript, jQuery Prototype - .

, :

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: . Kau-Boy

+1
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>
-1
source

Source: https://habr.com/ru/post/1749562/


All Articles