Javascript事件監聽1

來源:互聯網
上載者:User

firefox中addEventListener()方法和ie中attachEvent()方法都是為HTML元素添加一個事件監聽

為什麼要採用事件監聽而不是直接對元素的事件屬性(如:onclick、onmouseover)賦值?

這兩種方法處理事件還是有很大區別的!事件屬性只能賦值一種方法,即:

button1.onclick = function() { alert(1); };
button1.onclick = function() { alert(2); };
這樣後面的指派陳述式就將前面的onclick屬性覆蓋了。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Coda Bubble Example</title>
</head>
<body>
<button id="Button1">測試</button>
<script type="text/javascript">
/// <summary>
/// 添加事件監聽
/// </summary>
/// <param name="target">載體</param>
/// <param name="type">事件類型</param>
/// <param name="func">事件函數</param>
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;
}

/// <summary>
/// 移除事件監聽
/// </summary>
/// <param name="target">載體</param>
/// <param name="type">事件類型</param>
/// <param name="func">事件函數</param>
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 Button1Click = function() { alert(1); };
addEventHandler(Button1, "click",  Button1Click);
addEventHandler(Button1, "click", function() { alert(2); } );
addEventHandler(Button1, "click", function() { alert(3); } );

removeEventHandler(Button1, "click", function() { alert(2); } ); // 移不出
removeEventHandler(Button1, "click", Button1Click); // 可以移除
</script>
</body>
</html>

而添加事件監聽就可以並行。

特別是當團隊合作時,事件並行的需求增多,比如:監聽document對象的滑鼠事件或者window對象的載入事件等。
使用事件屬性則很容易造成事件覆蓋掉。

經過測試IE(8)中先顯示3再顯示2,而firefox(3)中則先顯示2再顯示3
這個是為什麼呢?測試的結果即真理,沒啥好想的。囧

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.