这是我的js代码,用于从数据库加载更多帖子的按钮。
.getmore
是按钮的类。现在,我想进行无限滚动,以便用户无需单击该按钮。
所以我添加了window.scroll
函数:
$('.getmore').trigger("click");
但它一次点击3次。手动点击按钮时,它可以正常工作。但是使用滚动触发器,它会变成三次相同的东西。
$(document).ready(function(){
$(window).scroll(function(){
if ($(window).scrollTop() + $(window).height() > $(document).height() - 300) {
$('.getmore').trigger("click");
}
});
$('body').on('click','.getmore',function(){
var lastelement = $(this).attr('id');
$.ajax({
type: 'GET',
url: 'getmore.php',
data:'lastelement='+lastelement,
beforesend: function(){
$('.getmore').html('loading....');
},
success: function(data){
$('.getmore').remove();
$('#recs') .append(data) ;
}
});
});
});
答案 0 :(得分:2)
正如MDN所说:
由于滚动事件可以以高速率触发事件处理程序 不应该执行计算上昂贵的操作,例如DOM 修改。相反,建议使用限制事件 requestAnimationFrame,setTimeout或customEvent
他们提出的基本方法是检查事件状态的全局变量。对于您的示例,您可以保存名为fetching
的全局变量,该变量在用户滚动时设置为true
,并在false
中完成新数据的提取时设置回success
{1}}回调。最后,不要让.getmore
点击"点击"如果fetching
是true
。
阅读文档以获取更多信息: https://developer.mozilla.org/en-US/docs/Web/Events/scroll
答案 1 :(得分:1)
尝试一下:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()){
$('yourbuttonIDorClass').trigger('click');
}
});
答案 2 :(得分:0)
这类问题的典型方法是使用演绎来排除导致问题的原因:。
排除类.getmore中有多少元素。
console.log($('.getmore').length);
//Add this line under the .trigger('click');
如果有> 1这可能是你的问题。
排除调用窗口滚动回调的次数。
console.log('Scroll called');
//Add this line at the start of your $(window).scroll function.
如果滚动被调用3次,则可能是您的问题
检查您所采取的事件委派方法是否会造成任何奇怪的问题。
将$('body').on('click', '.getmore', function() {}
替换为$('.getmore').click(function() {}