<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
var handler=function(){
alert(this.value);
}
var btn=document.getElementById("btn2");
//btn.addEventListener("click",handler,false);
var eventUtil={
//添加事件
addHandler:function(element,type,handler){
if(element.addEventListener){
element.addEventListener(type,handler,false);
}else if(element.attachEvent){
element.attachEvent('on'+type,handler);
}else{
element['on'+type]=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;
}
}
};
eventUtil.addHandler(btn,'click',handler);
</script>
</head>
<body>
<form action="">
<!-- <input type="button" value="Click me" onclick="try{showMessage();}catch(ex)()"> -->
<input type="button" value="button2" id="btn2">
</form>
</body>
</html>
或者将上面的script中的内容用window.onload封装
<script> ...........</script>应该放在body里面的<form></form>的后面,不然element的值为null。