Add a function to an anchor tag
I have several such anchor links as shown below.
<a href="http://google.com" onClick="unhook()"> Google </a>
I want to apply the onClick
event to all anchor tags dynamically. Is it possible?
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.net/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.com"> Google </a>
<a href="http://apple.com"> 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.com" onClick="unhook()"> Google </a>
<script>
$(".something").click(function(){
unhook();
});
</script>
Here I have used jQuery..don't forget to include jquery.js
.
精彩评论