内容添加了两次但只循环了一次

Content added twice though only looped once

我想使用 AJAX 向我的 Feed 添加更多内容,它确实添加了内容 - 但它添加了两次。为了排除像 AJAX 请求被提交两次这样的原因,我添加了整数 i。但是,如果我向下滚动,i 仅等于 1(如我的 h1 元素所述)。

AJAX success 函数接收一个 json 对象(我可以在警报中看到),然后将其转换为 html 两次(同一个对象和因此相同 html)。你知道为什么会出现这个问题吗?

jQuery:

function loadMore()
{
    var i = 0;
    var accountpar = $(".parent").length;

    $.ajax({
        url: 'homemore.php',
        type: 'post',
        data: {
            'account':accountpar
        },
        success: function(datanew) {
            i++;
            var datarec = datanew.replace(/},]$/,"}]");
            var string  = json2html.transform(datarec,template);
            alert(string);
            $(string).insertAfter($('.parent').last());
        }
    });
    $(window).bind('scroll', bindScroll);
}

function bindScroll(){
    if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
        $(window).unbind('scroll');
        loadMore();
    }
}

$(window).scroll(bindScroll);

尝试像这样在下面移动 i++

success: function(datanew) {
        $("h1").text(i);
        var datarec = datanew.replace(/},]$/,"}]");
        //alert(datarec);
        var string  = json2html.transform(datarec,template);
        $(string).insertAfter($('.parent').last());
        i++;
    }

而不是:

$(string).insertAfter($('.parent').last())

使用:

$('.parent').append($(string))

我会尝试这样的事情。我的感觉告诉我,它捕获 'by pixel' 并不止一次发射。您可以下载 debounce/throttle 插件并使用它,并将其设置为 250,或者试试这个 "once method"

如果使用去抖动(必须下载插件)

我重新阅读了你的post(在你更新之后),你绑定了两次: 曾经是这样的:

$(window).scroll(bindScroll);

再像这样:

$(window).bind('scroll', bindScroll);

我觉得这是一个危险信号。重读之后,我可能要么只是下载插件并将其包装在去抖动中($(window).scroll(bindScroll);)。


$.debounce( 250, bindScroll ) 

而不是这个:

 $(window).bind('scroll', bindScroll);

试试这个:

$( window ).one( "scroll", function() {
     bindScroll()
});