簡體   English   中英

jQuery / ajax無限滾動事件

[英]jquery/ajax infinite scroll event

我正在嘗試在我的Web應用程序上使用ajax,php,mysql進行自己的無限滾動。 但是,我找不到每當用戶到頁面末尾時都加載新內容的方法。

現在,它會在用戶點擊頁面末尾時立即加載所有數據。

有什么方法可以讓我的腳本“等到最后加載的頁面結束”。

$( ".places-wrapper ").scroll(function(){

var windowHeight = $( ".places-wrapper" ).height();
var documentHeight = $( ".places-wrapper")[0].scrollHeight;
var scrollFromTop = $( ".places-wrapper" ).scrollTop();
var margin = 70;

if( scrollFromTop >= documentHeight - windowHeight - margin){

loadNextPage();

}

function loadNextPage(){

    var PlaceID = $( "input[name='placeID']:last" ).val();
    var lastHitDate = $( "input[name='hitDate']:last" ).val();

    $.ajax({
        # .append the new stuff
           });

}

});

我猜您需要的是一個標志,以告訴您的腳本頁面正在加載。 您可以嘗試以下方法:

// add a variable as flag
var isLoading = false;

if( scrollFromTop >= documentHeight - windowHeight - margin){

     if ( !isLoading )
     {
        isLoading = true;
        loadNextPage();
     }    
}


// inside your ajax's success callback:

.success(function(){
    isLoading = false;

    // add the page contents
})

正如您可能猜到的那樣,您需要一個外部變量來打開和關閉“加載更多位置”。

var scrollActiveTimer = false;

$(".places-wrapper").scroll(function(){

    // Don't continue if a previous ajax request is still active
    if(scrollActiveTimer == true){
        return;
    }

    // For an improved performance you should try to minimize the jquery DOM searches    
    var wrapper = $(".places-wrapper");
    var windowHeight = wrapper.height();
    var documentHeight = wrapper[0].scrollHeight;
    var scrollFromTop = wrapper.scrollTop();
    var margin = 70;

    var scrollEndPosition = documentHeight - windowHeight - margin;

    if( scrollFromTop >= scrollEndPosition){
        loadNextPage();
    }

    function loadNextPage(){
        // Disable the loading of further pages for the moment
        scrollActiveTimer = true;

        var PlaceID = $("input[name='placeID']:last").first().val();
        var lastHitDate = $( "input[name='hitDate']:last" ).val();

        // Activate the loading event again
        scrollActiveTimer = false;

         $.ajax({
             // parameters..
         }).success(function(data){
             // copy data into html
             wrapper.append(data);

             // Activate the loading event again
             scrollActiveTimer = false;
         });
    }

});

我用一些虛擬函數來模擬ajax請求和html生成: http : //jsfiddle.net/Macavity/f77xmho7/2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM