简体   繁体   English

移除的EventListener仍然会触发

[英]Removed EventListener still fires

I have an event like so: 我有一个类似这样的事件:

var CountDemKeys;
document.body.addEventListener('keypress', function() { 
  CountDemKeys++;
  if (CountDemKeys % 10 === 0) {
    alert("WOO HOO!");
  }
});

and in a separate function: 并在一个单独的函数中:

RemoveShizzle = function() {
  document.body.removeEventListener('keypress');
};

But the event still fires :( 但是事件仍然会触发:(

note: I've also tried setting the event to null : document.body.addEventListener('keypress', null); 注意:我也尝试将事件设置为nulldocument.body.addEventListener('keypress', null);

document.body.addEventListener('keypress', null);

no joy... 不高兴...

you have to pass the same function as the second argument to removeEventListener . 您必须将与第二个参数相同的函数传递给removeEventListener

There could be other listeners attached to 'keypress' to the body element. 可能还有其他监听器附加到body元素的'keypress'上。

Thus, without supplying the original function, removeEventListener does not know which listener to remove. 因此,在不提供原始功能的情况下, removeEventListener不知道要删除哪个侦听removeEventListener

var CountDemKeys;
var listener = function() { 
  CountDemKeys++;
  if (CountDemKeys % 10 === 0) {
    alert("WOO HOO!");
  }
};
document.body.addEventListener('keypress', listener);

RemoveShizzle = function() {
  document.body.removeEventListener('keypress', listener);
};

You're most probably missing the second argument of removeEventListener . 您最有可能缺少removeEventListener的第二个参数。

Also please note that for MSIE support, you would need to use attachEvent 另外请注意,要获得MSIE支持,您需要使用attachEvent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM