PHP
·
发表于 5年以前
·
阅读量:8312
对于跨平台事件我们一般这么写(只例举添加事件):
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;
}
}
那么下面这段代码的效果是什么样的呢?
<div id="test">Test</div>
...
var oDiv=document.getElementById("test");
addEventHandler(oDiv,"mouseover",function(){
alert("over "+this.id);
});
由于IE的this问题,在IE中果断地弹出了 over undefined,所以跨平台的事件更好的写法是这样的:
function addEventHandler(oTarget, sEventType, fnHandler){
if(oTarget.addEventListener){
oTarget.addEventListener(sEventType,fnHandler,false);
} else if(oTarget.attachEvent){
oTarget.attachEvent("on"+sEventType,function(){
return fnHandler.call(oTarget,window.event);
});
} else{
oTarget["on"+sEventType]=fnHandler;
}
}