如何修复无限滚动JavaScript?

时间:2019-06-30 21:28:15

标签: javascript jquery

我正在尝试使用以下脚本无限滚动加载数据。初始数据正确加载,但似乎未检测到滚动。我尝试添加警报进行调试,但似乎找不到问题。后端页面 p_load.php 工作正常。知道可能是什么问题吗?

$(document).ready(function() {
    var track_load = 0; //total loaded record group(s)
    var loading  = false; //to prevents multipal ajax loads
    var total_groups = 2; //total record group(s)   

    $('#result').load("p_load.php?t=", {'group_no':track_load}, function() {track_load++;}); //load first group

    $(window).scroll(function() {
        if($(window).scrollTop() + $(window).height() >= $(document).height()) {
            alert("Detected scrolling"); //not working
            if(track_load <= total_groups && loading==false) //there's more data to load
            {
                loading = true; //prevent further ajax loading
                $('.animation_image').show(); //show loading image

                //load data from the server using a HTTP POST request
                $.post('p_load.php?t=',{'group_no': track_load}, function(data){

                    $("#result").append(data); //append received data into the element

                    //hide loading image
                    $('.animation_image').hide(); //hide loading image once data is received

                    track_load++; //loaded group increment
                    loading = false; 

                }).fail(function(xhr, ajaxOptions, thrownError) { //any errors?

                    alert(thrownError); //alert with HTTP error
                    $('.animation_image').hide(); //hide loading image
                    loading = false;

                });

            }
        }
    });
});

2 个答案:

答案 0 :(得分:1)

请尝试:

  $(document).on('scroll', function () {
    if(window.scrollY + window.innerHeight >= document.body.scrollHeight) {
        //your code
    };
  });

答案 1 :(得分:0)

您应该使用Intersection Observer API,这就是它的用途。

https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API