封裝兼容性添加、刪除事件的函數 addEventListener與removeEventListener


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="解除綁定">




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM