jQuery Facebook/Tumblr 风格的无限滚动条
这是代码:(感谢 hycus.com 的教程修改版本)
<script type="text/javascript">
var properlast=10;
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height()){
$("div#loadmoreajaxloader").show();
$.ajax({
url: "pinc-myactivity.php?start=" + properlast,
success: function(html){
if(html && $(".activity:last").attr("id") == properlast){
$("div#loadmoreajaxloader").before(html);
properlast = properlast+10;
$("div#loadmoreajaxloader").hide();
}else{
$("div#loadmoreajaxloader").html("<center>No more posts to show.</center>");
}
}
});
}
});
它一次拉十个活动帖子。效果很好,除了重复相同的十个帖子两次时遇到麻烦。
我放置了一个故障保护来告诉它最后一个帖子应该是什么(properlast 变量),根据实际的最后一个帖子 - $(".activity:last").attr("id") 检查它,并且仅当它匹配时然后发布 html 并将“properlast”变量增加十。
这很有帮助,但是当滚动速度非常快时,重复帖子仍然会发生 - 那么添加时间延迟可以解决这个问题吗?我觉得这不太理想,因为它根本不应该重复结果。
Here's the code: (modified version of a tutorial thanks to hycus.com)
<script type="text/javascript">
var properlast=10;
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height()){
$("div#loadmoreajaxloader").show();
$.ajax({
url: "pinc-myactivity.php?start=" + properlast,
success: function(html){
if(html && $(".activity:last").attr("id") == properlast){
$("div#loadmoreajaxloader").before(html);
properlast = properlast+10;
$("div#loadmoreajaxloader").hide();
}else{
$("div#loadmoreajaxloader").html("<center>No more posts to show.</center>");
}
}
});
}
});
It pulls ten activity posts at a time. Works great, except for trouble with it repeating the same ten posts twice.
I put a failsafe in to tell it what the last post should have been (properlast variable), check it against the actual last post - $(".activity:last").attr("id"), and only if it matches then post the html and increase the "properlast" variable by ten.
This helped, but repeating posts still occurs when scrolling really fast- so would adding a time delay fix it? I feel like that would be not as ideal because it shouldn't repeat results at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
避免重复元素的最简单方法是确保一次只有一个 ajax 请求正在运行。最好通过一个简单的布尔开关来完成
The simplest way to avoid duplicate elements is to ensure that there is only one ajax request in flight at a time. This is best done by a simple boolean switch