跨浏览器事件处理程序

<div id = "box">
<input type = "button" id = "btn" value = "按钮">
<input type = "button" id = "btn2" value = "按钮2">
<input type = "button" id = "btn3" value = "按钮3">
</div>
<script>
function showMes(){
alert("Hello World!");
}
var btn2 = Document.getElementById("btn2");
var btn3 = Document.getElementById("btn3");
//btn2添加点击事件
btn2.onClick = function(){
 alert("这是通过DOM0级添加的事件");
}
btn2.onClick = null;
//DOM2级事件
btn3.addEventListener("click",showMes,false);
btn3.addEventListener("click",function(){
   alert(this.value);
})
//删除事件
btn3.removeEventListener("click",showMes,false);
btn3.removeEventListener("click",function(){
   alert(this.value);
})
//IE事件
btn3.attachEvent("click",showMes);
btn3.detachEvent("click",showMes);
//跨浏览器事件处理
var eventUtil = {
//添加句柄
addHandler : function(element,type,hander){
if(element.addEventListener){
element.addEventListener(type,hander,false);
}
else if(element.attachEvent){
element.attachEvent('on'+type,hander);
}
else{
element["on"+type] = hander;
}
},
//删除句柄
removeHandler : function(element,type,hander){
if(element.removeEventListener){
element.removeEventListener(type,hander,false);
}
else if(element.attachEvent){
element.datachEvent('on'+type,hander);
}
else{
element["on"+type] = null;
}
}
}
eventUtil.addHandler(btn3,"click",showMes);
</script>

element.onClick==element["onClick"];

相关推荐