JS事件監聽器

樂哉樂哉發表於2013-02-06


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>

相關文章