要理解DOM 2级事件绑定方式的优点
标准浏览器中2级DOM事件绑定方式
IE中的处理方式
能够兼容IE和标准浏览器的代码:
var EventUtil = new Object;
EventUtil.addEventHandler = function(oTarget, sEventType, fnHandler) {
if (oTarget.addEventListener) {//ff
oTarget.addEventListener(sEventType, fnHandler, false);
oTarget.onclick = fnHandler;
} else if (oTarget.attachEvent) {//IE
oTarget.attachEvent("on" + sEventType, fnHandler);
} else {//照顾更老的浏览器,比如IE4
oTarget["on" + sEventType] = fnHandler;
}
};
EventUtil.removeEventHandler = function (oTarget, sEventType, fnHandler) {
if (oTarget.removeEventListener) {//FF
oTarget.removeEventListener(sEventType, fnHandler, false);
} else if (oTarget.detachEvent) {//IE
oTarget.detachEvent("on" + sEventType, fnHandler);
} else { //照顾更老的浏览器,比如IE4
oTarget["on" + sEventType] = null;
}
};