我有以下代码:
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');
您使用的函数根本没有意义,请注意您可以 namespace events稍后删除特定事件。
关于javascript - jQuery 自定义事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20455115/