Best way to add an event to an element without a library or using the onclick attribute?
So I want an element i.e: <a id="target">click me</a>
to perform a JavaScript function i.e:
functionName();
onclick=""
.
By cross-browser I mean the A-grade browser compatibility list 开发者_如何学Pythonfrom YUIvar el = document.getElementById("target");
var old = el.onclick;
el.onclick = function() {
if(old) old();
functionName();
// if you want to prevent default action
// return false;
};
For a more robust solution, see: Dean Edward's addEvent.
document.getElementById('target').onclick=function() {
functionName();
return false;
}
I assume you meant "without onclick html attribute"
Use the getElementById
method to find the element, and set it's onclick event:
document.getElementById('target').onclick = functionName;
I don't know if this counts as a library, but here are the addEvent() and removeEvent() functions written by John Resig (yes, that John Resig):
function addEvent( obj, type, fn )
{
if (obj.addEventListener)
{
obj.addEventListener( type, fn, false );
}
else if (obj.attachEvent)
{
obj["e"+type+fn] = fn;
obj[type+fn] = function() { obj["e"+type+fn]( window.event ); };
obj.attachEvent( "on"+type, obj[type+fn] );
}
}
function removeEvent( obj, type, fn )
{
if (obj.removeEventListener)
{
obj.removeEventListener( type, fn, false );
}
else if (obj.detachEvent)
{
obj.detachEvent( "on"+type, obj[type+fn] );
obj[type+fn] = null;
obj["e"+type+fn] = null;
}
}
Use:
addEvent(document.getElementById('target'), 'click', functionName);
removeEvent(document.getElementById('target'), 'click', functionName);
精彩评论