封装兼容性添加、删除事件的函数 addEventListener与removeEventListener

时间:2023-01-31 19:27:52
var Event = {
addHandler: function (oElement, sEvent, fnHandler) {
oElement.addEventListener ? oElement.addEventListener(sEvent, fnHandler, false) : oElement.attachEvent("on" + sEvent, fnHandler)
},
removeHandler: function (oElement, sEvent, fnHandler) {
oElement.removeEventListener ? oElement.removeEventListener(sEvent, fnHandler, false) : oElement.detachEvent("on" + sEvent, fnHandler)
}
}
window.onload = function ()
{
var aBtn = document.getElementsByTagName("input");

//为第一个按钮添加绑定事件
aBtn[1].onclick = function ()
{
Event.addHandler(aBtn[0], "click", fnHandler);
aBtn[0].value = "我可以点击了"
}

//解除第一个按钮的绑定事件
aBtn[2].onclick = function ()
{
Event.removeHandler(aBtn[0], "click", fnHandler);
aBtn[0].value = "毫无用处的按钮"
}

//事件处理函数
function fnHandler ()
{
alert("事件绑定成功!")
}
}
<input type="button" value="毫无用处的按钮"> <input type="button" value="绑定click"> <input type="button" value="解除绑定">