开发者

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();

I want to avoid using the "on" attributes i.e: onclick="".

By cross-browser I mean the A-grade browser compatibility list 开发者_如何学Pythonfrom YUI


var 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜