function addEventHandler(oTarget, sEventType, fnHandler) {
if (oTarget.addEventListener) {
oTarget.addEventListener(sEventType, fnHandler, false);
} else if (oTarget.attachEvent) {
oTarget.attachEvent("on" + sEventType, fnHandler);
} else {
oTarget["on" + sEventType] = fnHandler;
}
};
for(var i=0;i<10;i++)
{
var o=document.createElement("span");
o.setAttrbute("data",i);
addEventHandler(o,"click",function(){
alert(this.getAttribute("data"));
});
}
参考:http://www.quirksmode.org/blog/archives/2005/08/addevent_consid.html
还有:http://dean.edwards.name/weblog/2005/10/add-event/
一般通过event参数的target/srcElement来获取当前元素:
addEvent(el,"click",function (e) {
//this.className = '';
var node = (e) ? e.target : window.event.srcElement;
node.className = '';
});
if(!('bind'inFunction.prototype)){
Function.prototype.bind=function(owner){
var that=this;
var args=Array.prototype.slice.call(arguments,1);
returnfunction(){
return that.apply(owner,
args.length===0? arguments : arguments.length===0? args :
args.concat(Array.prototype.slice.call(arguments,0))
);
};
};
}