【问题标题】:How to remove an event listener from window?如何从窗口中删除事件监听器?
【发布时间】:2020-10-10 12:40:34
【问题描述】:

我正在构建一个蛇游戏,需要在空格键触发后删除一个事件监听器,但我没有得到任何运气,如下代码;

window.removeEventListener('keypress', (event) 

什么都不做。任何想法什么是正确的方法?谢谢

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

【问题讨论】:

    标签: javascript function if-statement events listener


    【解决方案1】:

    您需要对该函数的引用才能将其删除。不要使用匿名函数,而是:

    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);
    

    【讨论】:

      【解决方案2】:

      如果要删除事件侦听器,则必须将其定义为具有名称的函数,而不是像您所做的那样的内联函数。然后在添加时给出它的名称,在删除时给出它。

      这是因为一个元素可能对同一个事件有多个监听器。当您删除一个时,您必须指定哪一个。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-16
        • 2013-09-15
        • 2022-11-04
        • 1970-01-01
        • 2015-08-31
        • 1970-01-01
        • 2011-05-23
        相关资源
        最近更新 更多