jquery - 防止双击缩略图以确保内容不会通过 AJAX 加载两次

标签 jquery ajax click bind unbind

我有一个 jquery 函数,当我单击帖子缩略图时,它会加载帖子内容,效果很好。但如果我点击两次,内容就会加载两次。

我在某处读到,我需要取消绑定(bind)点击,并在内容加载完成后将其绑定(bind)回来。这是我的尝试。

现在似乎 event.preventDefault(); 被停用或发生其他情况,因为它在第二次单击时加载完整页面(而不是 AJAX 内容)。

$("a.ajaxed").on("click",function(event) {
    event.preventDefault();
    var self = this,
   // ...; other variables
    $(self).unbind("click"); // code line added 1of2
    $("#streamwrapper").fadeOut(1000, function(){
        $.ajax({
            type: "POST",
            dataType: "JSON",
            url: ajax_object.ajaxurl,
            data: ({
                action : "get_all_images",
                post_id: postid
                }),
            success:function(data){
                $("#board").append(postdiv);
                $("#post-container").append(data);
                postdiv.fadeIn(1000);
                $(self).bind("click"); // code line added 2of2
            },
            error:function(data){
                console.log(data);
            }
        });
    });
    return false;
});

最佳答案

我总是做的是使用 $(this).data 将“正在执行”标志附加到元素上。该函数首先检查是否设置了该标志,如果是则返回,否则设置该标志并在成功时清除它。以下内容应该满足您的要求:

$("a.ajaxed").on("click",function(event) {
   // ...; other variables

   var self = this; // needed for $(self).removeData below

   if ($(self).data('executing')) // if we're executing, return
       return;

    $(self).data('executing', true); // set executing flag

    $("#streamwrapper").fadeOut(1000, function(){
        $.ajax({
            type: "POST",
            dataType: "JSON",
            url: ajax_object.ajaxurl,
            data: ({
                action : "get_all_images",
                post_id: postid
                }),
            success:function(data){
                $("#board").append(postdiv);
                $("#post-container").append(data);
                postdiv.fadeIn(1000);

                $(self).removeData('executing'); // clear the executing flag
            },
            error:function(data){
                console.log(data);
            }
        });
    });
    return false;
});

关于jquery - 防止双击缩略图以确保内容不会通过 AJAX 加载两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12414147/

相关文章:

android - Android 中的 Button Click 上的 Long Click 事件触发

jquery - 通过纬度和经度按最近距离对地址列表进行排序

javascript - 单击时将文本元素转换为输入字段类型的文本,单击后又变回文本

html - HTML 规范本身的 API?或者简单的方法来获取规范?

php - 使用 PHP 和 AJAX 基于 Cookie 的民意调查

jquery - 调用方法,哪一种更好?

jquery - 单击两个下拉菜单

javascript - 检测shift键输入事件

javascript - 如何将点击事件绑定(bind)到点击事件时创建的元素?

IE11 中的 JavaScript 给我脚本错误 1003