当选项卡未激活时,如何防止Infinite Scroll加载页面?

时间:2019-02-15 14:07:03

标签: javascript jquery bootstrap-4 infinite-scroll

我在一个使用Bootstrap 4和jQuery的网站上工作,所以基本上有3个选项卡,每个选项卡都包含砖石元素,这些元素在使用Infinite Scroll插件滚动时加载。 我基本上是在寻找一种仅当选项卡处于活动状态时才允许无限滚动加载选项卡内容的方法。 因此,假设我的html如下所示:

<div class="tab-content" id="v-pills-tabContent">
    <div class="tab-pane fade show active" id="v-pills-home" role="tabpanel" aria-labelledby="v-pills-home-tab">
        <div class="grid" id="grid1">
            <!-- PHP script that generates the content for each element in that tab -->
        </div>                          
    </div>
    <div class="tab-pane fade" id="v-pills-profile" role="tabpanel" aria-labelledby="v-pills-profile-tab">
        <div class="grid2" id="grid2">
        <!-- second PHP script that generates the content for each element in that tab-->
        </div>
    </div>
    <div class="tab-pane fade" id="v-pills-messages" role="tabpanel" aria-labelledby="v-pills-messages-tab">
        <div class="grid3" id="grid3">
         <!-- third PHP script that generates the content for each element in that tab -->
        </div>
    </div>
</div>

要初始化砌体和无限滚动,我通过以下方式使用引导事件shown.bs.tab

$("#v-pills-profile-tab").on('shown.bs.tab', function () { 
    grid.infiniteScroll({
        path: '.pages'
        //other parameters
    });
});

但是,一旦初始化,Infinite Scroll不会在乎该选项卡是否不再显示,并且会继续在后台加载内容,这会弄乱我所有的砌体布局,并使网站不必要地加载内容。

所以我用$("#v-pills-profile")尝试了以下条件:

$("#v-pills-profile-tab").on('shown.bs.tab', function () 
{ 
    if($("#v-pills-profile").hasClass("active"))
    {
        grid.infiniteScroll({
            path: '.pages'
            //other parameters
        });
    }
}

但是问题仍然存在,好像Infinite Scroll被初始化了一次,即使$("#v-pills-profile")失去了它的“ active”类,它也会继续加载页面。

任何建议或帮助将不胜感激。 谢谢。

1 个答案:

答案 0 :(得分:0)

您是否尝试仅初始化已激活标签中包含的.grid元素?

$("#v-pills-profile-tab").on('shown.bs.tab', function() { 
    var activeGrid = $('.tab-pane.active').children('.grid');
    if (!InfiniteScroll.data(activeGrid[0])) {
        activeGrid.infiniteScroll({...});
    }        
}