2010-11-09 66 views
3

我有這樣的代碼:重置一個函數,或者停止某些操作並重新啓動它?

$(document).ready(function() { 
    var number = 10; 
    var offset = 10; 
    var page_number = 2;  

    /* Bind the scroll function to an event */ 
    $(window).bind('scroll', function(e) { 

     /* If the scroll height plus the window height is 
      more than the document height minus 10, continue */ 
     if($(window).scrollTop() + $(window).height() > 
      $(document).height() - 10) {   

      /* Quick message so you know more stuff is loading */ 
      $('.loading-more').html('Keep scrolling for more posts to load..');  

      $.post('<?php bloginfo('siteurl') ?>/wp-admin/admin-ajax.php', { 
       action: 'and_action', 
       off: offset+number, 
       pagenumber: page_number - 1 
       }, function(data) { 
        offset = offset+number;       
        $('.empty-div').append('<p><strong>Page '+page_number+'</strong></p><br />'+data); 
        page_number += 1;    
        $(this).unbind(e);           
      }); 
     }  
    }); 
}); 

此檢查用戶是否是靠近頁面和負載更多的內容的底部。問題在於,如果用戶在臨界點附近緩慢滾動,或者反覆滾動一遍又一遍,速度很快,則函數會運行幾次,這意味着您最終會加載一些我正在加載的數據實例。

我曾嘗試過的做法是綁定和解除綁定e變量,但它並沒有很好的工作。無論如何可能會運行一次函數post,然後重新設置函數,所以當用戶再次滾動時它會再次運行,所以不會加載一個以上的數據實例?

回答

1

你爲什麼不只是設置一個布爾值作爲當前狀態的表示:加載/就緒。

$(document).ready(function() { 
    var busy = false; 

    $(window).bind('scroll', function (e) { 
     if(!busy && goodposition){ 

      // load more 
      busy = true; 

      $.post(..., function(date){ 
      busy = false; 
      }); 
     } 
    }); 
}); 
1

爲什麼不去做這樣的事情:

var doingWork = false; 

if(($(window).scrollTop() + $(window).height() > $(document).height() - 10) 
    && !doingWork) 
{ 
    doingWork = true; 

然後重新doingWorkfalse,一旦你需要的功能回到

0

兩個答案建議通過設置一個布爾值來指出請求是否存在。這可能是我想要的路線。另一種選擇是取消現有的請求。

$.post返回XMLHttpRequest對象。這意味着您可以緩存請求對象並使用.abort()方法取消正在進行的請求:

$(window).bind('scroll', function(e) { 
    if($(window).scrollTop() + $(window).height() > 
     $(document).height() - 10) {   

     $('.loading-more').html('Keep scrolling for more posts to load..');  

     if (curxhr && (curxhr.readyState != 4) { // if the curxhr object exists and has not completed 
      curxhr.abort(); // abort the request 
     } 

     curxhr = $.post('<?php bloginfo('siteurl') ?>/wp-admin/admin-ajax.php', { 
      action: 'and_action', 
      off: offset+number, 
      pagenumber: page_number - 1 
      }, function(data) { 
       // snip          
     }); 
    }  
}); 
相關問題