JS事件監聽器

js事件監聽是學習js過程中必然要學習和掌握的。下面是js事件監聽的代碼
function addEventHandler(target, type, func) {
    if (target.addEventListener)
        target.addEventListener(type, func, false);
    else if (target.attachEvent)
        target.attachEvent("on" + type, func);
    else target["on" + type] = func;
}

有人問我,爲什麼我要用事件監聽呢?因爲我在target後面加一個.onclick或者.onmouseover 等等的事

件,各個瀏覽器都是完全兼容的啊。下面幾點就說明我們爲什麼要使用事件監聽器。
第一 :當同一個對象使用.onclick的寫法觸發多個方法的時候,後一個方法會把前一個方法覆蓋掉,也就

是說,在對象的onclick事件發生時,只會執行最後綁定的方法。而是用事件監聽則不會有覆蓋的現象,

每個綁定的事件都會被執行。但是IE家族先執行後綁定的方法,也就是逆綁定順序執行方法,其他瀏覽器

按綁定次數順序執行方法。

第二 :也是最重要的一點,採用事件監聽給對象綁定方法後,可以解除相應的綁定,寫法如下
function removeEventHandler(target, type, func) {
    if (target.removeEventListener)
        target.removeEventListener(type, func, false);
    else if (target.detachEvent)
        target.detachEvent("on" + type, func);
    else delete target["on" + type];
}


第三 :解除綁定事件的時候一定要用函數的句柄,把整個函數寫上是無法解除綁定的。看實例:
錯誤的寫法:
addEventHandler(Button1, "click", function() { alert("3"); } );
removeEventHandler(Button1, "click", function() { alert("3"); });

正確的寫法:
function test(){alert("3");}
addEventHandler(Button1, "click", test );
removeEventHandler(Button1, "click", test);

下面爲整個HTML代碼示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1.0-Transitional.dtd ">
<html xmlns="http://www.w3.org/1999/xhtml ">
<head>
<title>Javascript事件監聽</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<button id="Button1">測試</button>
<script type="text/javascript">
function addEventHandler(target, type, func) {
    if (target.addEventListener)
        target.addEventListener(type, func, false);
    else if (target.attachEvent)
        target.attachEvent("on" + type, func);
    else target["on" + type] = func;
}

function removeEventHandler(target, type, func) {
    if (target.removeEventListener)
        target.removeEventListener(type, func, false);
    else if (target.detachEvent)
        target.detachEvent("on" + type, func);
    else delete target["on" + type];
}

var Button1 = document.getElementById("Button1");
var test1 = function() { alert(1); };
function test2() {alert("2")}
addEventHandler(Button1,"click",test1);
addEventHandler(Button1,"click",test2 );
addEventHandler(Button1,"click", function() { alert("3"); } );
addEventHandler(Button1,"click", function() { alert("4"); } );

removeEventHandler(Button1,"click",test1);
removeEventHandler(Button1,"click",test2);
removeEventHandler(Button1,"click",function() { alert("3"); });
</script>
</body>
</html>

發佈了8 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章