[英]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.