javascript removeEventListener 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5825493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:29:34  来源:igfitidea点击:

removeEventListener is not working

javascriptevent-listener

提问by fogy

I don't know what I am doing wrong but here is an example of what I am doing and it doesn't seem to work.

我不知道我做错了什么,但这是我正在做的一个例子,它似乎不起作用。

someDom.addEventListener('mousemove',function(ev) {self.onInputMove(ev)},false);

someDom.removeEventListener('mousemove',self.onInputMove);

The removeEventListener code is executed but it just doesn't remove the 'mousemove' listener

执行 removeEventListener 代码,但它只是不删除“mousemove”侦听器

回答by Sean Vieira

removeEventListenerremoves the listener that exactlymatches the function that was added.

removeEventListener删除与添加的函数完全匹配的侦听器。

In this case, the function that addEventListeneradded was:

在这种情况下,addEventListener添加的函数是:

var some_func = function(ev) {
    self.onInputMove(ev);
};

Store a reference to the actual function and you'll be good. So for example, the following should work:

存储对实际函数的引用,你会很好。因此,例如,以下应该有效:

someDom.addEventListener('mousemove',self.onInputMove,false);

someDom.removeEventListener('mousemove',self.onInputMove,false);

回答by cem

onInputMoveis not an event-callback method. So you need to do something like:

onInputMove不是事件回调方法。因此,您需要执行以下操作:

var event = function(ev) {self.onInputMove(ev)};
someDom.addEventListener('mousemove', event,false);

someDom.removeEventListener('mousemove', event, false);

回答by Steffen Brem

Why make it yourself so hard, just use the following to bind an event to an element:

为什么自己弄这么难,就用下面的方法把一个事件绑定到一个元素上:

element.onmousemove = function(e) {
    // Some code here...
    alert("Mouse moved!");
};

Now, when you want to remove the event, just do this:

现在,当您想删除事件时,只需执行以下操作:

element.onmousemove = null;

Done!

完毕!

Hope this helps you guys out!

希望这对你们有帮助!

回答by daksh_019

This page comes first on searching this/such issue on Google. So apart from answers already mentioned, here is one more interesting fact for future:

此页面首先在 Google 上搜索此/此类问题。因此,除了已经提到的答案之外,还有一个更有趣的事实供未来参考:

Leaving out the third optional variable in addEventListener() for useCapture/useBubble (as it defaults to false) does create some issue while removing the same eventlistener with same callback name. I faced this issue while working on chrome. Cant say about other browsers.

为 useCapture/useBubble 省略 addEventListener() 中的第三个可选变量(因为它默认为 false)确实会在删除具有相同回调名称的相同事件侦听器时产生一些问题。我在处理 chrome 时遇到了这个问题。不能说其他浏览器。

So do mention the third variable explicitly as "false".

所以一定要明确提到第三个变量为“false”。