Remove EventListener in JavaScript after event occurred?

前端 未结 1 1369
轮回少年
轮回少年 2021-01-13 05:54

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.

相关标签:
1条回答
  • 2021-01-13 06:22

    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.

    0 讨论(0)
提交回复
热议问题