当用户滚动到底部时,下面的代码片段会加载下一页.但是,有时它会重复自己 – 当用户滚动太快时,或者在AJAX仍在加载时滚动.
有没有办法阻止它多次发射?例如,在调用AJAX时无法加载任何内容,或者只能每秒调用一次AJAX?
任何帮助都会很棒.
$(window).scroll(function() {
if( $(window).scrollTop() + $(window).height() == $(document).height()) {
if (firstURL !== null) {
$.get(firstURL,function(html) { // this gets called multiple times on erratic scrolling
firstURL = '';
var q = $(html).find('.post');
l = $(html).filter('div.bottom-nav');
if( l[0].childNodes.length > 0 ){
firstURL = l[0].children[0].getAttribute('href');
} else {
firstURL = null;
}
q.imagesLoaded( function() {
jQuery(".content").append(q).masonry( 'appended',q,true );
});
});
}
}
});
最佳答案
只需添加一个标志:
原文链接:https://www.f2er.com/jquery/428751.htmlvar ready = true; //Assign the flag here
$(window).scroll(function() {
//Check the flag here. Check it first,it's better performance wise.
if(ready && $(window).scrollTop() + $(window).height() == $(document).height()) {
ready = false; //Set the flag here
if (firstURL !== null) {
$.get(firstURL,function(html) { // this gets called multiple times on erratic scrolling
firstURL = '';
var q = $(html).find('.post');
l = $(html).filter('div.bottom-nav');
if( l[0].childNodes.length > 0 ){
firstURL = l[0].children[0].getAttribute('href');
} else {
firstURL = null;
}
q.imagesLoaded( function() {
jQuery(".content").append(q).masonry( 'appended',true );
});
}).always(function(){
ready = true; //Reset the flag here
});
}
}
});