在窗口滚动时触发AJAX加载,但如何阻止它反复加载相同的东西

时间:2012-03-19 12:11:39

标签: jquery ajax scroll

我有一个简单的AJAX函数,当用户向下滚动页面时会加载更多搜索结果。

$(window).scroll(function () { // fire the load stuff function as scroller gets near the bottom of the page
  if ($(window).scrollTop() >= parseInt($(document).height() - $(window).height() - 150)) {
       var finished = 1;
       if (finished == 1) {
          finished = 0;
          loadMore(function () { finished = 1; });
       };
    };
});

这很有效,除非它每次滚动窗口时触发loadMore函数,显然。

因此,检查Firebug控制台时,它会加载很多次。

在最后一个实例完成之前,它需要做的是不运行loadMore的另一个实例。

我尝试过放入一个回调和一个变量(你在代码中看到的finished变量),但这不起作用。

如何确保用户可以滚动,但该功能仅在没有此功能处理的其他实例时触发?

3 个答案:

答案 0 :(得分:2)

我认为这会有效,你需要在滚动事件外部设置完成,因为每次用户滚动时都会执行

var finished = 1;
        $(window).scroll(function () { // fire the load stuff function as scroller gets near the bottom of the page
      if ($(window).scrollTop() >= parseInt($(document).height() - $(window).height() - 150)) {           
           if (finished == 1) {
              finished = 0;
              loadMore(function () { finished = 1; });
           };
        };
    });

答案 1 :(得分:0)

您在函数中声明了finished变量 并将其值设置为1,因此您的if语句将始终评估为true。

finished设为全局而非本地,初始化为1,然后使用相同的代码。

答案 2 :(得分:0)

在body onload函数中声明finished,  之后你的滚动功能就可以开始了。

$(function(){
   finished=1;

   $(window).scroll(function () { 
// fire the load stuff function as scroller gets near the bottom of the page   
    if ($(window).scrollTop() >= parseInt($(document).height() - $(window).height() - 150)) 
    {         
       if (finished == 1) {           
           finished = 0;           
           loadMore(function () 
           { 
              finished = 1; 
           });        
       };     
    }; 
 }); 
 });