【发布时间】:2021-01-29 18:49:59
【问题描述】:
我正在尝试创建一个很好的加载更多帖子功能,当您在 div 容器中向下滚动页面时,当您到达容器末尾时,您会看到更多帖子。到目前为止,我尝试的工作正常,但是当我滚动速度非常快时出现错误,因为它发送了更多需要的 ajax 请求并正在加载重复的数据。
<!-- HTML Structure -->
<header style="position:fixed"></header>
<section class="page-banner" style="height: 420px;"></section>
<section class="projects-general">
<div class="projects-wrapper">
<div class="projects-list-wrap"></div>
</div>
</section>
<section class="contact-intro"></section>
<footer></footer>
<!-- HTML Structure -->
$(window).scroll(function() {
var pjCount = $('.pj-col').length;
var totalPj = $('#pj-numb').val();
if (pjCount >= totalPj){
return false;
}else{
if($(window).scrollTop() >= $('.projects-list-wrap').offset().top + $('.projects-list-wrap').outerHeight() - window.innerHeight + $('header').outerHeight()) {
jQuery.ajax({
url: ajaxURL,
type: "POST",
beforeSend: function () {
$('.projects-wrapper').append("<div class='pj-loader'></div>");
},
complete: function () {
$('.pj-loader').remove();
},
data:{
action: "pj_load_more",
pjCount:pjCount
},
success:function(data){
$('.projects-list-wrap').append(data);
},
error: function(err){
//console.log(err);
}
});
}
}
});
任何想法为什么当你尝试缓慢滚动时它是可以的,但是当你喜欢快速滚动时它会产生重复帖子的错误效果。 非常感谢
【问题讨论】:
-
取出 AJAX 调用并将
if条件中的值写入控制台。然后你可以看到为什么状态会/没有命中 -
@RoryMcCrossan 谢谢,正在尝试检查。
-
我真的很想用 this answer 作为副本来关闭它...请查看那里使用的条件以及它是否适合您。
-
我创建了一个CodePen,以便使用您提供的小代码测试您的状况。我“伪造”了一些 ajax 响应...请用缺少的内容编辑您的问题...因为“尝试重现”似乎表明您的代码正在运行。
-
顺便提一下,
<section class="page-banner" height: 420px;>是无效的 HTML。
标签: jquery ajax wordpress scroll