1

如果通过正常的页面加载加载,下面的 JS 代码可以正常工作。但是,如果包含此代码的页面通过 Ajax 刷新,则click注册多次,每次通过 Ajax 刷新页面时注册一次。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();                           
});
4

1 回答 1

1

你可以在打电话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();                           
});
于 2013-03-14T17:41:16.903 回答