JavaScript跨平臺(兼容各個平臺)事件

對于跨平臺事件我們一般這么寫(只例舉添加事件):

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;
    }
}

所屬標簽

無標簽

25选5玩法中奖