jQuery Infinite Scroll – 当滚动速度很快时,事件会多次触发

好的,下面的代码“有效”,当你滚动到页面底部时,会触发AJAX函数并将结果附加到页面上的#postswrapper div。

问题是:如果我到达页面底部时滚动非常快,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(); } } }); } }); 

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

 $(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,并且可以触发更多请求。