**跨浏览器的事件处理程序(各种浏览器均可兼容)**
面试必备@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>跨浏览器事件处理程序</title>
</head>
<body>
<button id="mybtn">点击我</button>
<script type="text/javascript">
//兼容所有浏览器
//addEventLister attachEvent
var EventUtil = {
addHandler: function (element,type,handler){
//绑定事件
//chrome ,firefox,IE9等,addEventLister
//IE8及IE8以下的浏览器 attachEvent
if (element.addEventListener){
element.addEventListener(type,handler,false);
}else if(element.attachEvent){
element.attachEvent("on",type,handler);
}else {
element["on"+type]=null
}
},
removeHandler : function (element,type,handler) {
//移除事件
//chrome ,firefox,IE9等,addEventLister
//IE8及IE8以下的浏览器 detachEvent
if(element.removeEventListener){
element.removeEventListener
}else if(element.detachEvent){
element.detachEvent("on",type,handler);
}else{
element["on"+type]=null
}
}
}
var btn=document.getElementById("mybtn");
var handler =function () {
alert("Clicked");
}
EventUtil.addHandler(btn,"click",handler);
</script>
</body>
</html>