簡體   English   中英

刪除動態附加的事件監聽器到元素

[英]remove dynamically attached event Listeners to elements

我將這些事件偵聽器動態附加到一個元素,如下所示:

const allTitles = document.querySelectorAll('.question-title');
allTitles.forEach(title => {
   title.addEventListener("click", (e) => {
      // some code goes here using e above
   });
});

我們如何刪除所有附加的事件偵聽器? 由於我們沒有引用每個偵聽器,它是 function,這似乎有點令人困惑。

只需將事件偵聽器添加到所有對象的父元素並偵聽父元素上的點擊

parentElement.addEventListener('click', (e) => {
     console.log(e.target) // this will be your title if you click on that, otherwise you can just return a falsy value
})

將事件偵聽器存儲在變量中。 然后您可以使用 removeElementListener 將其刪除。

var listeners = [];
allTitles.forEach(title => {
   var listener = (e) => {
      // some code goes here using e above
   });
   title.addEventListener("click", listener);
   listeners.push(listener);
});

然后,您可以像這樣刪除偵聽器:

title.removeElementListener(listeners[0]);

您可以使用添加它們的相同方式刪除它們,但使用removeEventListener 嘗試先給你用來添加名稱的 function 起一個名字,然后做這樣的事情

allTitles.forEach(title => {
  title.removeEventListener("click", onClickFunction});
});

你可以在這里閱讀更多關於它的信息

簡單的回答:不參考事件處理程序,我們不能。 至少不優雅。

唯一可行但蠻力的選擇是丟棄帶有附加偵聽器的原始元素並從頭開始重新創建它。 重新分配outerHTML可以做到這一點:

allTitles.forEach(title => {
  title.outerHTML = title.outerHTML; // nuke listeners
});

暫無
暫無

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

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