control123
2016-09-18 16:39
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
</head>
</head>
<body>
<div id="box">
<input type="button" value="按钮3" id="btn3" />
<a href="联系.html" id="go">跳转</a>
</div>
<script type="text/javascript">
var eventUtil={
addHandler:function(element,type,handler){
if(element.addEventListener){
element.addEventListener(type,showmes,false);
}else if(element.attachEvent){
element.attachEvent('on'+type,showmes);
}else{
element['on'+type]=showmes;
}
},
removeHandler:function(element,type,handler){
if(element.removeEventListener){
element.removeEventListener(type,showmes,false);
}else if(element.detachEvent){
element.detachEvent('on'+type,showmes);
}else{
element['on'+type]=null;
}
},
}
function showmes(){
alert('hello world');
}
function showbox(){
alert('这是放按钮的BOX');
}
function stopgoto(){
alert('');
}
var btn3=document.getElementById('btn3');
var box=document.getElementById('box');
var go=document.getElementById('go');
eventUtil.addHandler(btn3,'click',showmes);
eventUtil.addHandler(box,'click',showbox);
</script>
</body>
</html>
错误:你addHandler里面所有的handler都用的showmes,所以不管绑定什么函数,都是showme。
解决办法:把addHandler中所有showmes改为handler。removeHandler中亦是如此。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
</head>
<body>
<div id="box">
<input type="button" value="按钮3" id="btn3" />
<a href="联系.html" id="go">跳转</a>
</div>
<script type="text/javascript">
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;
}
},
}
function showmes(){
alert('hello world');
}
function showbox(){
alert('这是放按钮的BOX');
}
function stopgoto(event){
event.stopPropagation();
event.preventDefault();
}
var btn3=document.getElementById('btn3');
var box=document.getElementById('box');
var go=document.getElementById('go');
eventUtil.addHandler(btn3,'click',showmes);
eventUtil.addHandler(box,'click',showbox);
eventUtil.addHandler(go,'click',stopgoto);
</script>
</body>
</html>
试一下吧!
var eventUtil={ addHandler:function(element,type,handler){ //这里参数是handler if(element.addEventListener){ element.addEventListener(type,showmes,false); //错误,将showmes改成handler }else if(element.attachEvent){ element.attachEvent('on'+type,showmes); //错误 }else{ element['on'+type]=showmes; //错误 } }
DOM事件探秘
99544 学习 · 1197 问题
相似问题