簡體   English   中英

如何從 window 中刪除事件監聽器?

[英]How to remove an event listener from window?

我正在構建一個貪吃蛇游戲,需要在空格鍵觸發后刪除一個事件監聽器,但我沒有像下面的代碼那樣走運;

window.removeEventListener('keypress', (event) 

什么都不做。 任何想法什么是正確的方法? 謝謝

window.addEventListener('keypress', (event) => {
  console.log(event)
  if (event.key === ' ') {
    startGame()
    window.removeEventListener('keypress', (event))
  }
})

您需要引用 function 才能將其刪除。 不要使用匿名函數,而是:

function handleKeyPress(event){
  console.log(event)
  if (event.key === ' ') {
    startGame()
    window.removeEventListener('keypress', (event))
  }
})

//add it
window.addEventListener('keypress',handleKeyPress);
//remove it
window.removeEventListener('keypress',handleKeyPress);

如果您要刪除事件偵聽器,則必須將其定義為帶有名稱的 function,而不是像您所做的那樣將其定義為內聯 function。 然后在添加和刪除時給出它的名稱。

那是因為一個元素可能對同一個事件有多個監聽器。 當您刪除一個時,您必須指定是哪一個。

暫無
暫無

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

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