使用事件委托的建议:
(function()
{
function callback(e)//IE doesn't pass event object, but we'll fix that
{
var target;
e = e || window.event;//get IE event
target = e.target || e.srcElement;//IE again
if (target.tagName !== 'A')
{
return true;
}
//a link has been clicked, target holds a reference to that link, e is the click event
alert(target.href);
//to prevent the link to be followed:
if (e.preventDefault)
{// all major browsers, except for ie
e.preventDefault();
e.stopPropagation();
return false;
}//now IE again:
e.returnValue = false;
e.cancelBubble = true;
return false;//not required to return here
}
if (document.body.addEventListener)
{
document.body.addEventListener('click',callback,false);
}
else
{
document.body.attachEvent('onclick',callback);//for IE > 9
}
})();
这样,您只需将 1 个事件侦听器绑定到 1 个处理程序,它会处理在页面上任何位置单击的所有链接。如果您只想阻止/处理某些链接,您可以给它们一个不同的类,并像这样编辑回调函数:
if(target.tagName !== 'A')
//add extra check:
if (target.tagName !== 'A' && target.className !== 'handleThisLinkClass')
google JavaScript 事件委托,这是一个非常有用的功能,尤其是在处理需要事件处理程序的大量元素时