2011-08-03 65 views
20

好的,下面的代码“工作”,当你滚动到页面底部时,AJAX函数被触发,结果被附加到#postswrapper div上页。jQuery Infinite Scroll - 当滚动速度很快时事件触发多次

问题是:如果我滚动的速度非常快,当我到达页面底部时,AJAX会多次触发并将几组结果加载到#postswrapper div中(另外的“不需要的”结果的数量由通过快速滚动来触发多少额外的滚动事件)。

最终,每次用户到达底部时,我只需要提供一组结果。我试过添加计时器等,但无济于事。很明显,在DOM中存储额外的滚动操作,然后按顺序将它们触发。

任何想法?

我正在使用jquery.1.4.4.js,如果这有助于任何人。无论如何,在这种情况下,e.preventDefault()不起作用。

$(window).scroll(function(e) { 
    e.preventDefault(); 
    if ($(window).scrollTop() >= ($(document).height() - $(window).height())) { 
     $('div#loadmoreajaxloader').show(); 
     $.ajax({ 
      cache: false, 
      url: 'loadmore.php?lastid=' + $('.postitem:last').attr('id'), 
      success: function(html) { 
       if (html) { 
        $('#postswrapper').append(html); 
        $('div#loadmoreajaxloader').hide(); 
       } else { 
        $('div#loadmoreajaxloader').html(); 
       } 
      } 
     }); 
    } 
}); 
+1

不需要的结果是'loadmore.php'脚本在没有必要时会被执行几次额外的时间。我只需要,每次用户到达页面底部时,该块代码运行一(1)次,通过loadmore.php加载适当的结果,并且在用户到达页面底部之前不加载任何其他内容再次。 – Marc

回答

42

尝试存储某种数据来存储页面当前是否正在加载新项目。也许是这样的:

$(window).data('ajaxready', true).scroll(function(e) { 
    if ($(window).data('ajaxready') == false) return; 

    if ($(window).scrollTop() >= ($(document).height() - $(window).height())) { 
     $('div#loadmoreajaxloader').show(); 
     $(window).data('ajaxready', false); 
     $.ajax({ 
      cache: false, 
      url: 'loadmore.php?lastid=' + $('.postitem:last').attr('id'), 
      success: function(html) { 
       if (html) { 
        $('#postswrapper').append(html); 
        $('div#loadmoreajaxloader').hide(); 
       } else { 
        $('div#loadmoreajaxloader').html(); 
       } 
       $(window).data('ajaxready', true); 
      } 
     }); 
    } 
}); 

发送Ajax请求权之前,一个标志被清除标志着该文件还没有准备好更多的Ajax请求。一旦Ajax成功完成,它会将标志设置为true,并且可以触发更多的请求。

+2

是的哥们!我早些时候有类似的逻辑,但你钉了它。 工程就像一个魅力。干杯! – Marc

+0

只是偶然发现了这个,并且效果很好 - 谢谢! –

+0

真棒破解,谢谢!我将问题中的代码和解决相同问题的答案结合起来,谢谢! – Hugo