<html> <head> <title>Add/Remove Event Handlers Example</title> <script type="text/javascript"> // addEventListener 是JS自带函数 // attachEvent 是JS自带函数 var EventUtil = new Object; EventUtil.addEventHandler = function (oTarget, sEventType, fnHandler) { if (oTarget.addEventListener) { // 如果还没有绑定click事件,则进行绑定。页面载入时候会执行这里。 oTarget.addEventListener(sEventType, fnHandler, false); } else if (oTarget.attachEvent) { // 查看绑定了什么事件 oTarget.attachEvent("on" + sEventType, fnHandler); } else { oTarget["on" + sEventType] = fnHandler; } }; EventUtil.removeEventHandler = function (oTarget, sEventType, fnHandler) { if (oTarget.removeEventListener) { oTarget.removeEventListener(sEventType, fnHandler, false); } else if (oTarget.detachEvent) { oTarget.detachEvent("on" + sEventType, fnHandler); } else { oTarget["on" + sEventType] = null; } }; // 最后起作用的函数 function handleClick() { alert("Click! d"); var oDiv = document.getElementById("div1"); // EventUtil.removeEventHandler(oDiv, "click", handleClick); } // 绑定DIV与触发事件,以及函数体 window.onload = function() { var oDiv = document.getElementById("div1"); EventUtil.addEventHandler(oDiv, "click", handleClick); } </script> </head> <body> <div id="div1" style="background-color: red; 100px; height: 100px"><font size="30" color="white">sss</font></div> </body> </html>