关于向下滚动javascript问题的脚本



我有一个javascript脚本,可以在页面向下滚动时加载更多信息。问题是,当我向下滚动时,脚本会执行两次,而我会得到两次甚至更多的相同结果。

我希望每次向下滚动时执行一次脚本,而不是每次执行两次甚至更多。

这是脚本:

$(window).scroll(function(){
			
var lastID = $('.load-more').attr('lastid');
if ($(window).scrollTop() == $(document).height() - $(window).height() && lastID != 0){
$.ajax({
type:'POST',
url:'getdata.php',
data:'id='+lastID,
beforeSend:function(html){
$('.load-more').show();
},
success:function(html){
$('.load-more').remove();
$('#list').append(html);
}
});
}
});
		

试试这个

var counter  = 0;

$(window).scroll(function(){
var lastID = $('.load-more').attr('lastid');
if ($(window).scrollTop() == $(document).height() - $(window).height() && lastID != 0 && counter < 1){
counter++;
$.ajax({
type:'POST',
url:'getdata.php',
data:'id='+lastID,
beforeSend:function(html){
$('.load-more').show();
},
success:function(html){
// reset counter to 0 after you get your results
counter = 0;
$('.load-more').remove();
$('#list').append(html);
}
});
}
});
$(window).one('scroll',function(){ ...}
..

jquery文档中"one"的解释:每个事件类型的每个元素最多执行一次处理程序。http://api.jquery.com/one/函数将只在第一次滚动时执行,第二次和任何后续时间都不会发生任何事情。

您可以等到上一个加载完成后再加载新的。

var isLoading
$( window ).on( 'scroll', onScroll )
function onScroll() {
if( isLoading ) return
isLoading = true
$.ajax({
success: function() {
isLoading = false
// Add content, etc...
}
})
}

再添加一个测试,这样在加载程序显示时可以忽略滚动

if (
$(window).scrollTop() === $(document).height() - $(window).height()
&& +lastID !== 0
// fancy way to say "Is this element in the DOM" w/ good performance
&& $.contains(document.documentElement, $('.load-more')[0])
) {
// then load more content
}

迷你Rant

我将==更改为===,并明确地将lastID强制为一个数字,这也允许将!=更改为!==

当自动类型强制不能提供任何明显的好处时,避免它只是一个好习惯。这个语言特性本身并没有什么不好的地方。然而,尽可能采取合理的步骤来避免它,将使代码更容易理解,并使jit编译器更容易优化。当我在自己的代码中发现类似==的东西时,它的外观是自我记录的,让我知道我有意利用类型强制来达到有目的的效果(其他节省1个小按键(。

注意:所选的检查元素存在的方法来自SLaks在对这个答案的评论中提供的jsPerf。

var timeout;
$(window).scroll(function() {
clearTimeout(timeout);  
timeout = setTimeout(function(){
var lastID = $('.load-more').attr('lastid');
if ($(window).scrollTop() == $(document).height() - $(window).height() && lastID != 0){
$.ajax({
type:'POST',
url:'getdata.php',
data:'id='+lastID,
beforeSend:function(html){
$('.load-more').show();
},
success:function(html){
$('.load-more').remove();
$('#list').append(html);
}
});
}
}, 200);
});

滚动的第二次执行将触发功能延迟执行的取消,并启动不会被任何东西取消的另一次执行。

最新更新