繁体   English   中英

jQuery自定义事件监听器

[英]jQuery custom event listener

我有以下代码:

myCustomMethod(function(){
    $(document).on('click','#element',function(){
        console.log('First call');
    });
});

setTimeout(function(){
    myCustomMethod(function(){
        $(document).on('click','#element',function(){
            console.log('Second call, event first call should be destroyed');
        });
    });
},2000);


function myCustomMethod(funcn){
    funcn();            
}

当我用浏览器测试时,我点击了#element console show up First call

但是2秒后我再次点击它显示

First call
Second call, event first call should be destroyed

我想删除事件监听器(如果它被修改)(下面的部分)

Old

$(document).on('click','#element',function(){
    console.log('First call');
});

New

$(document).on('click','#element',function(){
    console.log('Second call, event first call should be destroyed');
});

只触发console.log('Second call, event first call should be destroyed');

非常感谢

添加事件处理程序不会删除以前的事件处理程序,它只会添加更多,这就是为什么不删除旧的事件处理程序。

您可以使用off()来删除jQuery中的事件处理程序

$(document).on('click.custom', '#element', function(){
    console.log('First call');
});

setTimeout(function(){
    $(document).off('click.custom').on('click.newclick','#element',function(){
        console.log('Second call, event first call should be destroyed');
    });
},2000);

删除您要执行的特定事件的所有先前处理程序

$(document).off('click');

您正在使用的功能根本没有任何意义,请注意您可以命名事件以在以后删除特定事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM