事件发生后,在JavaScript中删除EventListener? [英] Remove EventListener in JavaScript after event occurred?

查看:90
本文介绍了事件发生后,在JavaScript中删除EventListener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}

问题在于 removeEventListener 嵌套在 addEventListener 中,我需要将类型,监听器,标题定义为 removeEventListener 方法。而且我认为由于嵌套而无法定义监听器。

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

}


推荐答案

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

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。如果你关心速度,你可能希望考虑只使用一个事件处理程序。您可以将处理程序放入div的父元素中,然后从那里委派事件。使用24个处理程序,您当前的方法可能没有很大的性能影响,但如果感觉很慢,这应该记住。

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.

这篇关于事件发生后,在JavaScript中删除EventListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆