jQuery Infinite Scroll - event fires multiple times when scrolling is fast

前端 未结 1 475
我寻月下人不归
我寻月下人不归 2021-01-30 11:48

Okay, the code below \"works\" in that when you scroll to the bottom of the page the AJAX function is fired and results are appended to the #postswrapper div on the page.

<
相关标签:
1条回答
  • 2021-01-30 12:03

    Try storing some kind of data that stores whether the page is currently loading new items. Maybe like this:

    $(window).data('ajaxready', true).scroll(function(e) {
        if ($(window).data('ajaxready') == false) return;
    
        if ($(window).scrollTop() >= ($(document).height() - $(window).height())) {
            $('div#loadmoreajaxloader').show();
            $(window).data('ajaxready', false);
            $.ajax({
                cache: false,
                url: 'loadmore.php?lastid=' + $('.postitem:last').attr('id'),
                success: function(html) {
                    if (html) {
                        $('#postswrapper').append(html);
                        $('div#loadmoreajaxloader').hide();
                    } else {
                        $('div#loadmoreajaxloader').html();
                    }
                    $(window).data('ajaxready', true);
                }
            });
        }
    });
    

    Right before the Ajax request is sent, a flag is cleared signifying that the document is not ready for more Ajax requests. Once the Ajax completes successfully, it sets the flag back to true, and more requests can be triggered.

    0 讨论(0)
提交回复
热议问题