jQuery 仅在选项卡单击时加载页面一次

标签 jquery jquery-tabs jquery-load

我有一个页面,上面有一些选项卡,单击某些选项卡后,其他页面会动态加载。唯一的问题是每次单击选项卡时都会加载这些页面。如何让它们在第一次点击时仅加载一次?

我使用的代码是这样的:

$(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;
    });
});

谢谢!

最佳答案

使用.data()保存 bool 值。

$(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;
    });
});

关于jQuery 仅在选项卡单击时加载页面一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3509712/

相关文章:

javascript - jquery Accordion - 如何在页面加载时默认打开第二个选项卡

jquery - 如何在jquery中计算 "visible"选项卡?

javascript - jQuery $(window).height 动态添加内容错误

javascript - 防止通过 jquery.load() 加载时重定向脚本

javascript - 将现有的 div 放在现有的 div 上,然后在它们之间切换

javascript - 给定一个日期/时间字符串,使用 javascript/jquery,如何确定它是否是今天?

jquery:选择具有给定名称和值的输入

jquery - 使整个 div 可点击

jquery - 单击新选项卡时页面跳转到顶部(jQuery 选项卡)

jquery - 使用jQuery的.load()加载页面片段但只获取选择器的内容