Mar*_*arc 21 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();
}
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
Mat*_*ley 46
尝试存储某种数据,用于存储页面当前是否正在加载新项目.也许是这样的:
$(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);
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
在发送Ajax请求之前,将清除一个标志,表示该文档尚未准备好接收更多Ajax请求.一旦Ajax成功完成,它就会将标志设置为true,并且可以触发更多请求.