<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div>
<input type="button" id="btn3" value="按钮3">
</div>
<script>
function showMsg(){
alert('Hello world!');
}
//browser compatible
var eventUtil={
//add handler
addHandler:function(element,type,handler){
if(element.addEventListener){
//dom2 level
element.addEventListener(type,handler,false);
}else if(element.attachEvent){
//ie
element.attachEvent('on'+type,handler);
}else{
//dom0 level
//在js中所有用.连接属性的时候都可以用[],element.onclick === element['onclick']
element['on'+type] = handler;
}
},
//remove handler
removeHandler:function(element,type,handler){
if(element.removeEventListener){
element.removeEventListener(type,handler,false);
}else if(element.detachEvent){
element.detachEvent('on'+type,handler);
}else{
element['on'+type] = null;
}
}
};
//call object
eventUtil.addHandler('btn3','click',showMsg);
//eventUtil.removeHandler('btn3','click',showMsg);
</script>
</body>
</html>