事件发生后在 JavaScript 中删除 EventListener?

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

Remove EventListener in JavaScript after event occurred?

javascriptjavascript-events

提问by einstein

There are 24 div-objects waiting/listening for a mouse-click. After click on one div-object, I want to remove the EventListenerfrom all 24 div-objects.

有 24 个 div 对象等待/监听鼠标点击。单击一个 div 对象后,我想EventListener从所有 24 个 div 对象中删除。

for (var i=1;i<=24;i++){
    document.getElementById('div'+i).addEventListener('click',function(event){
        for (var z=1;z<=24;z++){
            document.getElementById('div'+z).removeEventListener()//Problem lies here
        }

        //Some other code to be run after mouseclick

        },false);

}

The problem is that the removeEventListeneris nested in addEventListenerand I need to define type, listener, caption as attributes to the removeEventListenermethod. And I think it is impossible to define the listener because of nesting.

问题是removeEventListener嵌套在addEventListener,我需要定义类型、侦听器、标题作为removeEventListener方法的属性。而且我认为由于嵌套,无法定义侦听器。

I also tried to define a function name, but it didn't worked:

我也尝试定义一个函数名,但没有奏效:

for (var i=1;i<=24;i++){
    document.getElementById('div'+i).addEventListener('click',function helpme(event){
        for (var z=1;z<=24;z++){
            document.getElementById('div'+z).removeEventListener('click',helpme,false);
        }

        //Some other code to be run after mouseclick

        },false);

}

回答by Jani Hartikainen

It should work with a named function. If your second approach does not work properly, try storing the initial listener into a variable, like this:

它应该与命名函数一起使用。如果您的第二种方法不能正常工作,请尝试将初始侦听器存储到变量中,如下所示:

var handler = function(event) {
    for(...) {
        removeEventListener('click', handler, false);
    }
};

addEventListener('click', handler, false);

Ps. if you care about speed, you may wish to consider using just one event handler. You can put the handler into the parent element of the divs, and then delegate the event from there. With 24 handlers your current approach probably doesn't have a very big performance hit, but this is something you should keep in mind if it ever feels slow.

附言。如果您关心速度,您可能希望考虑仅使用一个事件处理程序。您可以将处理程序放入 div 的父元素中,然后从那里委托事件。使用 24 个处理程序时,您当前的方法可能不会对性能造成很大的影响,但是如果感觉很慢,您应该记住这一点。