<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>跨浏览器事件处理程序</title>
</head>
<body>
<input type="button" value="按钮" id="btn">
<script type="text/javascript">
function showMes(){
alert("hello!");
}
var btn=document.getElementById("btn");
var eventUtil={
//添加句柄
addHandler:function(element,type,handler){
if(element.addEventListener){ //DOM 2级判断
element.addEventListener(type,handler,false);
}
else if(element.attachEvent){ //IE事件处理程序判断
element.attachEvent('on'+type,handler);
}
else{ HTML事件处理程序
element['on'+type]=handler; //element.onclick===element['onclick']
}
},
//删除句柄
removeHandler:function(element,type,handler){
if(element.removeEventListener){ //DOM 2级判断
element.removeEventListener(type,handler,false);
}
else if(element.detachEvent){ //IE事件处理程序判断
element.detachEvent('on'+type,handler);
}
else{ HTML事件处理程序
element['on'+type]=null;
}
}
}
eventUtil.addHandler(btn,'click',showMes);
// eventUtil.removeHandler(btn,'click',showMes);
</script>
</body>
</html>