How do I add an onclick event to html tags without id's using javascript?
I tried doing this but it didn't seem to work:
window.onload = initAll;
function initAll(){
document.getElementsByTagName('a').onclick = clickHandler;
}
function clickHandler(){
if(this.toString().indexOf("localhost") < 0) {
confirmation = confirm("You are now leaving http://soso.com. Please click 'ok' to continue开发者_开发百科 to this site, or 'cancel' to stay in http://soso.com");
if (confirmation == false){
return false;
}
}
}
I know I can getElementById and that works, but it doesnt work this way. Any help would be appreciated.
Thanks!
document.getElementsByTagName('a') returns a NodeList of DOM Elements. So for starters, you will have to iterate over them and attach a handler to each like this :
var links = document.getElementsByTagName('a');
for( var i=0,il = links.length; i< il; i ++ ){
links[i].onclick = clickHandler;
}
If there are many elements, I suggest you read about event delegation and assign just one handler for everything.
function initAll()
{
var elements = document.getElementsByTagName('a'); // returns an array
// add the handler to each element
var n;
for (n = 0; n < elements.length; ++n)
elements[n].onclick = clickHandler;
}
That's because getElementsByTagName
returns a NodeList
. You cannot assign an event handler via the onclick
property on a NodeList
, only a single DOMElement
.
Try:
var elems = document.getElementsByTagName('a');
for (var i = 0; i < elems.length; i++) {
elems[i].onclick = clickHandler;
}
You need to iterate over all of the elements returned by document.getElementsByTagName
var links = document.getElementsByTagName('a');
var i = links.length;
while ( i-- ) {
links[i].onclick = clickHandler;
}
// ... rest of your code ...
I'd strongly suggest using JQuery. Something like this should do the trick:
$(function(){$('a').click(clickHandler);});
精彩评论