【问题标题】:jQuery: really simple self-made infinite scrolljQuery:真正简单的自制无限滚动
【发布时间】:2023-04-08 23:12:01
【问题描述】:

我知道那里有多个插件,但我想知道如何让自己的东西按我想要的方式工作。

首先,当滚动到我的页面底部时,我想触发一个名为 ajaxLoadActivity 的函数,该函数现在由“显示更多”按钮触发。

$(window).scroll(function() {

            if ( $(window).scrollTop() >= ( $(document).height() - $(window).height() ) )

                if ( $('ol.astream > .loadCount:last > li').attr('id') == "noMoreActivities" )
                    return false;

                ajaxLoadActivity('bottom', true);
                console.log('fired');

        });

我遇到的问题可能是每个人在尝试自己执行此操作时都会遇到的。问题是该函数被多次触发。函数ajaxLoadActivity 完成所有的ajax 工作并将<li> 项附加到现有的<ol>。仅将其与“显示更多”按钮一起使用时,该功能就可以完美运行。

但是我想知道如何在简单地滚动到页面底部时触发相同的功能。但我只想调用它一次 - 然后等到加载的东西 - 并且只有在再次到达底部时才允许再次触发该函数。

上面的示例代码中已经有一个异常......如果我的最后一个元素的 id 为 noMoreActivities,我不希望再次触发该函数,因为这样就没有更多的活动了。

有什么想法可以只触发一次函数并等待请求发生吗?

【问题讨论】:

    标签: ajax jquery scroll infinite-scroll


    【解决方案1】:

    假设您正在使用 $.post,您可以在您的 ajaxLoadActivity 函数中返回它,然后检查它是否正在运行

    var ajax;
    
    $(window).scroll(function() {
    
        if ( $(window).scrollTop() >= ( $(document).height() - $(window).height() ) )
    
            if ( $('ol.astream > .loadCount:last > li').attr('id') == "noMoreActivities" )
                return false;
    
            if (ajax) {
    
                return false; // don't make another request, let the current one complete, or
                // ajax.abort(); // stop the current request, let it run again
            }
    
            ajax = ajaxLoadActivity('bottom', true);
            console.log('fired');
    
    });
    
    function ajaxLoadActivity(one, two) {
    
        return $.post(/* stuff */);
    }
    

    【讨论】:

    • 但这只会触发一次,对吧?因此,如果我滚动到底部,则调用该函数,但是一旦我再次到达底部,我希望该函数再次触发
    • $(document).height() 将发生变化,因此应该再次被解雇
    • 会不会有人解释为什么你使用这个特殊条件: $(document).height() - $(window).height() ) 当滚动顶部 - 在页面底部 - 不总是看起来比 document.height -window.height 大?为什么不直接使用 scrolltop ===document.height?
    【解决方案2】:

    $(window).scrollTop() == ( $(document).height() - $(window).height() ) 将使它只执行一次调用。试试看。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      相关资源
      最近更新 更多