javascript 如何删除javascript中的事件侦听器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15100576/
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-26 23:29:59  来源:igfitidea点击:

How to remove an event listener in javascript?

javascriptjquerytouch

提问by FairyQueen

I am wondering how can I remove an event listener after adding one, the way you use on and off in jquery?

我想知道如何在添加事件侦听器后删除事件侦听器,就像您在 jquery 中打开和关闭的方式一样?

document.removeEventListener('touchstart');
document.addEventListener('touchstart', function (e) {
     closePopupOnClick(e, popup);
});

but this does not actually remove the event listener. If I put the addEventListener code in a function and pass that function into the the removeEventListener it will not work bc you cannot pass params into the function. Anyone know how to do this?

但这实际上并没有删除事件侦听器。如果我将 addEventListener 代码放在一个函数中并将该函数传递给 removeEventListener 它将不起作用 bc 你不能将参数传递到函数中。有人知道怎么做吗?

回答by Paul S.

Put the listener as a variable and attach via .addEventListener

将侦听器作为变量并附加通过 .addEventListener

var myListener = function (e) {
    closePopupOnClick(e, popup);
};
document.addEventListener('touchstart', myListener, true);

then pass it again when removing with .removeEventListener

然后在删除时再次传递它 .removeEventListener

document.removeEventListener('touchstart', myListener);


If you're notin strict mode you can make a listener remove itself with arguments.callee

如果你不是在严格模式下,你可以让一个监听器移除自己arguments.callee

document.addEventListener('touchstart', function (e) {
    closePopupOnClick(e, popup);
    document.removeEventListener('touchstart', arguments.callee);
}, true);

If you are in strict mode, you have to use a named function expressionif you want a function to remove itself

如果你在严格模式下,如果你想要一个函数删除自己,你必须使用一个命名的函数表达式

document.addEventListener('touchstart', function myListener(e) {
    closePopupOnClick(e, popup);
    document.removeEventListener('touchstart', myListener);
}, true);


If you want to use variables in the listener that may be changed by something (e.g. a loop), then you can write a generator function, for instance

如果你想在监听器中使用可能被某些东西(例如循环)改变的变量,那么你可以编写一个生成器函数,例如

function listenerGenerator(popup) {
    return function (e) {
        closePopupOnClick(e, popup);
    };
}

Now you can create the listener with listenerGenerator(popup)and it will scope the popupvariable. Note that if popupis an Object, it will be ByRefand therefore may still be subject to changes.

现在您可以使用listenerGenerator(popup)它创建侦听器,它将作用域popup变量。请注意,如果popupObject,它将是ByRef,因此可能仍会发生变化。