<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
<input type="button" value="按钮" id="btn" onclick="showMessage()">
<input type="button" value="按钮2" id="btn2">
<input type="button" value="按钮3" id="btn3">
</div>
<script>
function showMessage(){
alert('hello world!');
}
var btn2=document.getElementById('btn2');
var btn3=document.getElementById('btn3');
btn2.onclick=function(){
alert('这是通过Dom0触发的事件!');
}
btn2.onclick=null;
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(btn3,'click',showMessage);
</script>
</body>
</html>
<script> function showMessage(){ alert('hello world!'); } var btn2=document.getElementById('btn2'); var btn3=document.getElementById('btn3'); btn2.onclick=function(){ alert('这是通过Dom0触发的事件!'); } btn2.onclick=null; 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(btn3,'click',showMessage); </script>
var eventUtil={ 少了个 结束的花括号 }