老师我想尝试用一下兼容性代码,为什么会报错?
报错信息:
Uncaught TypeError: Cannot read property 'addEventListener' of undefined
at Object.addHandle
js代码:
var eventComp = {
addHandle: 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]=null;
}
},
removeHandle: 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;
}
},
getTarget: function(event){
return event.targat || event.srcElement;
},
preventDefault: function(event){
if (event.preventDefault) {
event.preventDefault();
}else{
event.returnValue = false;
}
},
stopPropagation: function(event){
if (event.stopPropagation) {
event.stopPropagation();
}else{
event.cancelBubble = true;
}
}
};
var ul1=document.getElementsByTagName('ul')[0];
var fun = function(event){
alert(getTarget(event));
};
eventComp.addHandle(ul1,'click',fun);
HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="eventComp.js"></script>
</head>
<body>
<ul>
<li id='1'>111</li>
<li id='2'>222</li>
<li id='3'>333</li>
<li id='4'>444</li>
<li id='5'>555</li>
<li id='6'>666</li>
</ul>
</body>
</html>
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星