簡體   English   中英

事件傳播和多個事件處理程序

[英]Event Propagation and Multiple Event Handlers

好吧,我很困惑。 我在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;
};

如何讓較低的事件觸發並達到較高的事件,然后取消該事件?

看看我在這里的意思

哈,呵呵。 使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM