我制作了一个jQuery脚本,用户在滚动时从数据库中加载项目。唯一的问题是,当用户在页面加载后非常快速地滚动时,脚本的结果会翻倍,因此来自数据库的信息会显示两次。不确定这里发生了什么,但脚本在下面。顺便说一句,这一切都在doc准备好了。
function last_item_funtion()
{
var ID=$(".newsItem:last").attr("id");
$('#feedLoader').html('<img src="../files/images/bigLoader.gif" style="display:block;margin-left:auto;margin-right:auto;">');
$.post("AJAX/scroll_feed.php?action=get&last_item_id="+ID,
function(data){
if (data != "") {
$(".newsItem:last").after(data);
}
$('#feedLoader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
last_item_funtion();
}
});
这不是我的jsfiddle,但它简要地说明了脚本的作用。它没有显示我遇到的问题,但我无法复制,因为我无法将整个数据库放在jsfiddle上。
更新 玩完游戏后,我意识到当用户进行一次连续滚动而不是短滚动时,用户不会在页面加载后直接滚动。从此我猜测jQuery没有注册数据已加载,直到滚动停止。
答案 0 :(得分:0)
尚未对此进行测试,但请查看这是否解决了您的问题
$(window).die("scroll").live("scroll",function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
last_item_funtion();
}
});
答案 1 :(得分:0)
好吧,我想多次触发scroll
事件,所以请求多次完成。请尝试以下方法:
function bind_scroll() {
$(window).bind('scroll', function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$(window).unbind('scroll');
last_item_funtion();
}
});
}
function last_item_funtion() {
var ID = $(".newsItem:last").attr("id");
$('#feedLoader').html('<img src="../files/images/bigLoader.gif" style="display:block;margin-left:auto;margin-right:auto;">');
$.post("AJAX/scroll_feed.php?action=get&last_item_id=" + ID,
function (data) {
if (data != "") {
$(".newsItem:last").after(data);
}
$('#feedLoader').empty();
bind_scroll();
});
};
bind_scroll();
它绑定scroll
事件,并在触发后解除绑定。请求完成后,事件再次绑定。
(您也可以查看jQuery.one(),但我从未使用过它。)
修改强>
在做了一些测试之后,即使我们取消绑定,滚动事件也会被触发很多,所以这里有一个更新的例子,它使用全局变量来告诉scroll
- 如果它已经加载了某些内容的回调,或者它是否可以做一个新的帖子请求:
window.scroll_loading = false;
function last_item_funtion() {
var ID = $(".newsItem:last").attr("id");
$('#feedLoader').html('<img src="../files/images/bigLoader.gif" style="display:block;margin-left:auto;margin-right:auto;">');
$.post("AJAX/scroll_feed.php?action=get&last_item_id=" + ID,
function (data) {
window.scroll_loading = false;
if (data != "") {
$(".newsItem:last").after(data);
}
$('#feedLoader').empty();
}
);
};
$(window).bind('scroll', function () {
if (window.scroll_loading == true) {
return;
}
if ($(window).scrollTop() > $(document).height() - $(window).height() - 10) {
window.scroll_loading = true;
console.log("FIRE!");
last_item_funtion();
}
});