0

好的,我很困惑。我在document上有一個全局的單擊事件處理程序。在網頁上我有幾個鏈接。每個鏈接由相同的單擊事件處理程序處理,除此之外,它們可以防止事件冒泡到文檔級別並阻止鏈接執行。在這些鏈接中,有一個具有特定的點擊處理程序,它是假設做它的事情,然後將事件傳遞給鏈接的通用點擊事件。但事實並非如此。事件傳播和多事件處理程序

document.onclick = function() 
    { 
    document.body.innerHTML += "You clicked me!"; 
}; 

    document.getElementsByTagName("a")[0].onclick = function(e) { 
    this.innerHTML += " Click it!"; 
    e.stopPropagation(); 
    //This return false appears only to 
    //prevent the link from its default action 
    return false; 
    }; 
document.getElementById("link").onclick = function(e) { 
    this.innerHTML += " Go ahead, "; 
    //But this return false appears to stop 
    //the propagation up to the previous event 
    //I would think that removing the link below 
    //would cause the event to propagate to the event 
    //above which would then stop the propagation and 
    //prevent the default, but apparently this is 
    //not the case; removing the line below causes 
    //the link to load Google like normal 
    return false; 
}; 

如何獲得較低的觸發事件,且到上的事件,然後取消該事件?

明白我的意思here

+0

不幸的是我沒有時間,現在寫了一個詳細的答案,但這種聯繫可能有助於解釋:HTTP://www.quirksmode .org/js/events_order.html –

+0

謝謝@詹姆斯,那個鏈接很有幫助。幸運的是,我自己設法弄清了我的問題。謝謝! :) –

+1

僅供參考:DOM級別0事件(前綴爲「開」)只接受一個處理程序。你壓倒了它。此外,你可能會發現'document.links'有助於遍歷。 – 2011-07-20 19:58:12

回答

1

哈,真不錯。使用element.on<event>就是簡單地在元素的DOM中設置屬性,這意味着每個事件只能有一個處理程序。相反,我需要使用addEventListener與正確使用event.preventDefault()event.stopPropagation()

在我第一次嘗試結合起來,我把我想成爲第一個處理程序第二,但真正意味着它是壓倒一切的首位。在這種情況下,我需要首先放置我想要的處理程序,因爲處理程序正在附加到事件。

我修改後的代碼應該是:

document.onclick = function() 
    { 
    document.body.innerHTML += "You clicked me!"; 
}; 
document.getElementById("link").addEventListener("click",function() { 
    this.innerHTML += " Go ahead, "; 
}); 
    document.getElementsByTagName("a")[0].addEventListener("click",function(e) { 
    this.innerHTML += " Click it!"; 
    e.stopPropagation(); 
    e.preventDefault(); 
    }); 

http://jsbin.com/ecozep/8/edit