当用户滚动到页面末尾时使用jQuery .load()

当用户滚动到页面底部时,我正在使用jQuery load()来加载更多内容。 这是我的剧本。

$(window).scroll(function () { if ($(window).scrollTop() >= $(document).height() - $(window).height()) { var visible_posts = $('.post').length - 1; $(".posts").append('
'); $(".more-content-" + visible_posts).html('
'); $(".more-content-" + visible_posts).load('/ajax/get_posts.php?offset=' + visible_posts); } });

问题是这会产生奇怪的行为和许多加载GIF,如果用户的滚动速度太快..我认为因为它附加div加载div每次和每次条件满足甚至在加载完成之前。

问题是:

有没有办法在第一次执行后停止脚本..运行load()…然后重新启用该function? 当您要禁用太快的点击时,类似于解除绑定的内容。

任何的想法?

如何在加载完成后重新启用该function?

 var canLoad = true; $(window).scroll(function () { if ($(window).scrollTop() >= $(document).height() - $(window).height() && canLoad) { canLoad = false; // other stuff $(".more-content").load('stuff', function() { // re-enable scroll function canLoad = true; }); } }); 

一旦开始加载新页面就设置一个标志,并在页面更新后取消设置。

 var loadingMore = false; $(window).scroll(function () { if ( !loadingMore && $(window).scrollTop() >= $(document).height() - $(window).height()) { loadingMore = true; var visible_posts = $('.post').length - 1; $(".posts").append('
'); $(".more-content-" + visible_posts).html('
'); $(".more-content-" + visible_posts) .load('/ajax/get_posts.php?offset=' + visible_posts, function(){loadingMore = false;} ); } });

重要的是要注意,它不仅仅是多次出现的div,实际上是在发出多个AJAX请求。

试试这个

 var flag = true; $(window).scroll(function () { if ($(window).scrollTop() >= $(document).height() - $(window).height()) { if(flag){ flag = false; var visible_posts = $('.post').length - 1; $(".posts").append('
'); $(".more-content-" + visible_posts).html('
'); $(".more-content-" + visible_posts).load('/ajax/get_posts.php?offset=' + visible_posts, function(){ flag = true }); } } });

这应该有用,我还添加了评论来帮助你:

 $(window).scroll(function () { var bload = 1; // Add a boolean var if ($(window).scrollTop() >= $(document).height() - $(window).height() && bload) { // Check in the condition to see if we load bload = 0; // Set the boolean to false or zero, so that we don't load anything else until the var is true again var visible_posts = $('.post').length - 1; $(".posts").append('
'); $(".more-content-" + visible_posts).html('
'); $(".more-content-" + visible_posts).load('/ajax/get_posts.php?offset=' + visible_posts, function () { bload = 1; // This gets fired when the load is done, so we can load again (we set the bool to true) }); } });