如果通过正常页面加载来加载,下面的 JS 代码可以正常工作。但是,如果包含此代码的页面通过 Ajax 刷新,则 click
会被注册多次,每次通过 Ajax 刷新页面时都会注册一次。您可以通过打印“Saved”一词的次数或通过 console.log
消息“#SavedBtn clicked”出现的次数来判断。
通过 Ajax 加载页面时,是否有某种方法可以取消设置点击处理程序?
HTML:
<button type='button' id='saveBtn'></button>
JS:
$(document.body).on('click', '#saveBtn', function(){
var t='<span class="savedSpan">Saved</span>';
$(this).after(t);
console.log('#saveBtn clicked');
$('.savedSpan').animate({
color: "#FFF4D2"
}, 1000).fadeOut();
});
最佳答案
您可以调用off()
在调用 on()
之前。这将在添加另一个处理程序之前删除该处理程序。
代码可能如下所示:
$(document.body).off('click', '#saveBtn');
$(document.body).on('click', '#saveBtn', function(){
var t='<span class="savedSpan">Saved</span>';
$(this).after(t);
console.log('#saveBtn clicked');
$('.savedSpan').animate({
color: "#FFF4D2"
}, 1000).fadeOut();
});
关于javascript - 使用 jQuery on() 时取消 Ajax 之后的事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15416398/