jQuery load page only once on tab click

扶醉桌前 提交于 2019-12-23 01:36:51

问题


I have a page with some tabs on it and upon clicking on certain tabs, other pages are loaded dynamically. The only problem is that these pages load every time the tabs are clicked on. How do I make them load only once, at the first click?

The code that I use is this:

$(document).ready(function(){
    $(".tab-content").hide();
    $("#one").show();

    $("a.tab-name").click(function(){
        $(".tab-name-active").removeClass("tab-name-active");
        $(this).addClass("tab-name-active");
        $(".tab-content").fadeOut();
        var content_show=$(this).attr("title");

        if (content_show === 'three') {
            $("#"+content_show).load('new-page.php', function() {
                $("#sorttable").tablesorter({
                    headers: {0: {sorter: false}}
                });
            });
        }
        else if (content_show === 'four') {
            $("#"+content_show).load('new-page-2.php');
        }

        $("#"+content_show).delay(100).fadeIn('slow');

        return false;
    });
});

Thanks!


回答1:


use .data() to save a boolean value.

$(document).ready(function(){
    $(".tab-content").hide();
    $("#one").show();

    $("a.tab-name").data('loaded',false).click(function(){
        var $this = $(this);
        $(".tab-name-active").removeClass("tab-name-active");
        $this.addClass("tab-name-active");
        $(".tab-content").fadeOut();
        var content_show= this.title;

        if (! $this.data('loaded')) {

          if (content_show === 'three') {
            $("#"+content_show).load('new-page.php', function() {
                $("#sorttable").tablesorter({
                    headers: {0: {sorter: false}}
                });
                $this.data('loaded',true);
            });
          }
          else if (content_show === 'four') {
            $("#"+content_show).load('new-page-2.php', function(){
                $this.data('loaded',true);
            });
          }

        } 

        $("#"+content_show).delay(100).fadeIn('slow');

        return false;
    });
});



回答2:


I just did a feature like this yesterday. The way I did it though was add a "still_loading" class in an arbitrary div(say your container div) then when the tab finally loads, remove that class again.



来源:https://stackoverflow.com/questions/3509712/jquery-load-page-only-once-on-tab-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!