禁用Jquery / JS函数

时间:2017-07-24 05:53:46

标签: javascript jquery javascript-events

我有一个函数,只要用户滚动并点击页面底部(如facebook),就会从数据库中加载新的新数据。现在的问题是,当用户滚动到底部时,向上滚动一点,然后再次向下滚动到底部:这会将函数调用两次吗?因此,加载新帖子两次。

我喜欢的是在激活时暂时禁用该功能,加载新数据,然后再启用该功能。

这是我的代码:

function scroll_load() {
   $('#maincontainer').bind('scroll', function(){
     If($(this).scrollTop()+$(this).innerHeight()>=$(this)[0].scrollHeight){
       //CODE THAT TEMPORARILY DISABLES THE SCROLLING FUNCTION UNTIL AJAX LOADS SUCCESSFULLY here--



       //loads the new posts through ajax
       $.ajax({
          type: 'GET',
          url: "getpost.php",
          data: {'id':my_id},

          success: function(data){
             $('#dataview').append(data);
          }
       });
     }
   });

}

谢谢!

3 个答案:

答案 0 :(得分:1)

我希望这会有所帮助

   var isScrolled = false;
            function scroll_load() {
if(isScrolled == false){
           $('#maincontainer').bind('scroll', function(){
             If($(this).scrollTop()+$(this).innerHeight()>=$(this)[0].scrollHeight){
               //CODE THAT TEMPORARILY DISABLES THE SCROLLING FUNCTION UNTIL AJAX LOADS SUCCESSFULLY here--



               //loads the new posts through ajax
               $.ajax({
                  type: 'GET',
                  url: "getpost.php",
                  data: {'id':my_id},

                  success: function(data){
                     $('#dataview').append(data);
                  }
               });
             }
           });
        IsScrolled = true;
}
        }

您可以使用超时功能将IsScrolled值再次设置为False

答案 1 :(得分:1)

function scroll_load() {

   var throttled = false;
   var scrollDelay = 350;

   $('#maincontainer').bind('scroll', function(){
     If($(this).scrollTop()+$(this).innerHeight()>=$(this)[0].scrollHeight){
       //CODE THAT TEMPORARILY DISABLES THE SCROLLING FUNCTION UNTIL AJAX LOADS SUCCESSFULLY here--


       if (!throttled) {

        throttled = true;
        //loads the new posts through ajax
       $.ajax({
          type: 'GET',
          url: "getpost.php",
          data: {'id':my_id},

          success: function(data){
             $('#dataview').append(data);
          }
       });

        //  we don't allow to our function to execute more than once every X milliseconds
        setTimeout(function (){
          throttled = false;
        }, scrollDelay);
      }
     }
   });

}

答案 2 :(得分:1)

您可以使用旗帜。当您调用该函数时,该标志将为1,当您收到返回的数据时,标志将为0,如下所示:

var flag = 0;
function scroll_load() {

   $('#maincontainer').bind('scroll', function(){
     if(flag) return;
     else {

       flag = 1;

       If($(this).scrollTop()+$(this).innerHeight()>=$(this)[0].scrollHeight){
       //loads the new posts through ajax
       $.ajax({
          type: 'GET',
          url: "getpost.php",
          data: {'id':my_id},

          success: function(data){
          flag = 0;
          $('#dataview').append(data);
      }
   });
 }
   });
}