JS 解决 removeEventListener 不生效问题

1,811 阅读1分钟
  • 在使用 addEventListener 添加监听后,需要通过 removeEventListener 移除通知,但是不生效,所以需要注意: 添加移除 的监听方法要一致,也就是监听绑定的是哪个 function,移除也得一致。

  • 无法移除的写法

    // 添加消息监听
    window.addEventListener('message', function (msg) {
      // 输出
      console.log(msg)
      // 移除消息监听
      window.removeEventListener('message', function (msg) {
        // 输出
        console.log(msg)
      }, false)
    })
    
  • 可以移除的写法

    // 添加消息监听
    window.addEventListener('message', receiveMessage)
    // 接收消息
    function receiveMessage (msg) {
      // 输出
      console.log(msg)
      // 移除消息监听
      window.removeEventListener('message', receiveMessage, false)
    }