admin管理员组

文章数量:1310136

I have several such anchor links as shown below.

<a href="" onClick="unhook()">  Google </a>

I want to apply the onClick event to all anchor tags dynamically. Is it possible?

I have several such anchor links as shown below.

<a href="http://google." onClick="unhook()">  Google </a>

I want to apply the onClick event to all anchor tags dynamically. Is it possible?

Share Improve this question edited Sep 9, 2010 at 7:03 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Sep 4, 2010 at 8:03 shantanuoshantanuo 32.2k91 gold badges263 silver badges431 bronze badges 0
Add a ment  | 

6 Answers 6

Reset to default 5

Using vanilla javascript:

function onclickHandler() {
  //do stuff
}

window.onload=function() {
  var aTags=document.getElementsByTagName('A');
  for (var i=aTags.length-1; i>=0; i--) {
    if(aTags[i].onclick) {
      var oldOnClick = aTags[i].onclick;
      aTags[i].onclick = function() {
        onclickHandler.call(this);
        oldOnClick.call(this);
      }
    } else {
      aTags[i].onclick = onclickHandler;
    }
  }
}

Check here: http://jsfiddle/496af/1/ (Updated with the code edits.)

This can be done fairly easily with jQuery:

$('a').bind('click', unhook);

This code selects all a tags and binds the unhook function to the click event.

And even shorter (thanks KennyTM):

$('a').click(unhook);

If you really want to add the click handler to all links, you can access them with document.anchors:

var anchors = document.anchors;
for(var i = 0, l = anchors.length;i < l;i++) {
    anchors[i].onclick = unhook;
}

I use traditional event handling here as it should work in all browsers. There are other, more advanced ways to add handlers, but it differs a bit between IE and other browers (but of course it is not impossible ;)).

What you can do is wrap all these A in a DIV and set the click event once ont that DIV and not on all A.

<div onclick="unhook(event||window.event);return false;">
    <a href="http://google.">  Google </a>
    <a href="http://apple.">  Apple </a>
</div>

<script>
    function unhook(e){
        var elm = e.target || e.srcElement;
        //do the unhook, ie:
        elm.parentNode.removeChild(elm);
    }
</script>

You can do that using jQuery

1.

$('a').click( function() {
   // your unHook code here
} );

Or 2.

$('a').click( unHook() );

or if you don't want to use jQuery, then simply you can use.

allAnchors = document.getElementsByTagName ( 'a' );
for ( i = 0 ; i < allAnchors.length; i++ ){
   allAnchors[i].onClick = unHook;
}

Yes, put it inside a loop or add a class to all anchors and bind the click event to that function:

<a class='something' href="http://google." onClick="unhook()">  Google </a>
<script>
    $(".something").click(function(){
        unhook();

    });
</script>

Here I have used jQuery..don't forget to include jquery.js.

本文标签: javascriptAdd a function to an anchor tagStack Overflow