Remove EventListener in JavaScript after event occurred?

梦想的初衷 提交于 2019-12-20 01:09:53

问题


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

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 removeEventListener is nested in addEventListener and I need to define type, listener, caption as attributes to the removeEventListener method. And I think it is impossible to define the listener because of nesting.

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);

}

回答1:


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.



来源:https://stackoverflow.com/questions/3723914/remove-eventlistener-in-javascript-after-event-occurred

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!