jQuery load page only once on tab click

2019-05-30 20:08发布

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!

2条回答
女痞
2楼-- · 2019-05-30 20:34

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.

查看更多
不美不萌又怎样
3楼-- · 2019-05-30 20:55

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;
    });
});
查看更多
登录 后发表回答