<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Document</title><style type="text/css">#goSomewhere{background:green;}#doSomewhere{background:blue;}#sayHi{background:red;}</style></head><body><ul id = "mylinks"><li id="goSomewhere">Go somewhere</li><li id="doSomewhere">Do something</li><li id="sayHi">Say hi</li></ul></body><script type="text/javascript">var item1=document.getElementById("goSomewhere");var item2=document.getElementById("doSomewhere");var item3=document.getElementById("sayHi");EventUtil.addHandler("click",function(event){location.href = "http://www.wrox.com";})EventUtil.addHandler(item2,"click",function(event){document.title="I changed the document's title";})EventUtil.addHandler(item3,"click",function(event){alert("hi");})</script></html>
2 回答
已采纳
FSYu
TA贡献152条经验 获得超59个赞
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; } }, getEvent: function(event) { return event ? event : window.event; }, getTarget: function(event) { return event.target || event.srcElement; }, preventDefault: function(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } }, stopPropagation: function(event) { if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubbles = true; } }, getRelatedTarget: function(event) { if (event.relatedTarger) { return event.relatedTarget; } else if (event.toElement) { return event.toElement; } else if (event.fromElement) { return event.fromElement; } else { return null; } } }
这个你写了吗,如果没写,EventUtil不能直接用
cnyballk
TA贡献148条经验 获得超93个赞
那你能不能说一下你为什么要用EventUtil。你是要兼容浏览器监听事件吧,做之前最好先理解下还有学会看报错,不然肯定会出问题,先定义EventUtil
-----------
刚看到有人回答问题了,,啊哈哈我不献丑了 ,你用他那个吧 比我全多了
addHandler: function(element, type, handler){ //若浏览器支持addEventListener,则使用addEventListener来添加事件 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; } } }
添加回答
举报
0/150
提交
取消