【问题标题】:How do I keep the current tab active with twitter bootstrap after a page reload?页面重新加载后,如何使用 twitter bootstrap 保持当前选项卡处于活动状态?
【发布时间】:2012-05-18 09:38:36
【问题描述】:

我目前正在使用带有 Twitter Bootstrap 的选项卡,并希望在用户发布数据并重新加载页面后选择相同的选项卡。

这是怎么做到的?

我当前对 inti 选项卡的调用如下所示:

<script type="text/javascript">

$(document).ready(function() {

    $('#profileTabs a:first').tab('show');
});
</script>

我的标签:

<ul id="profileTabs" class="nav nav-tabs">
    <li class="active"><a href="#profile" data-toggle="tab">Profile</a></li>
    <li><a href="#about" data-toggle="tab">About Me</a></li>
    <li><a href="#match" data-toggle="tab">My Match</a></li>
</ul>

【问题讨论】:

标签: javascript jquery twitter-bootstrap


【解决方案1】:

您必须使用 localStorage 或 cookie 来管理它。这是一个快速而肮脏的解决方案,可以大大改进,但可以为您提供一个起点:

$(function() { 
    // for bootstrap 3 use 'shown.bs.tab', for bootstrap 2 use 'shown' in the next line
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        // save the latest tab; use cookies if you like 'em better:
        localStorage.setItem('lastTab', $(this).attr('href'));
    });

    // go to the latest tab, if it exists:
    var lastTab = localStorage.getItem('lastTab');
    if (lastTab) {
        $('[href="' + lastTab + '"]').tab('show');
    }
});

【讨论】:

  • 不错的一个萌芽,你的解决方案可能会添加到joomla 30核心中,joomlacode.org/gf/project/joomla/tracker/…
  • 最好使用$(this).attr('href') 而不是$(e.target).attr('id'),这会为您提供没有完整网址的哈希值。您还必须在带有data-toggle="tab" 的标签上应用.tab(),而不是$('#'+lastTab)。另见:stackoverflow.com/questions/16808205/…
  • 看起来方法在 Bootstrap 3 中略有变化。shown 似乎不再有效,必须将其更改为 shown.bs.tab。注意:我了解 javascript 等,也了解经济学......所以知道发生了什么的人请随时纠正我。
  • 修改为使用多个选项卡控件(和 Bootstrap 3):gist.github.com/brendanmckenzie/8f8008d3d51c07b2700f
  • 进入第一个标签页,刷新后返回当前标签页
【解决方案2】:

使用 cookie 使其工作,并从任何其他选项卡和选项卡窗格中删除“活动”类...并将“活动”类添加到当前选项卡和选项卡窗格。

我确信有更好的方法可以做到这一点,但这似乎在这种情况下有效。

需要 jQuery cookie 插件。

$(function() { 
  $('a[data-toggle="tab"]').on('shown', function(e){
    //save the latest tab using a cookie:
    $.cookie('last_tab', $(e.target).attr('href'));
  });

  //activate latest tab, if it exists:
  var lastTab = $.cookie('last_tab');
  if (lastTab) {
      $('ul.nav-tabs').children().removeClass('active');
      $('a[href='+ lastTab +']').parents('li:first').addClass('active');
      $('div.tab-content').children().removeClass('active');
      $(lastTab).addClass('active');
  }
});

【讨论】:

  • 我无法让 localStorage 解决方案正常工作,尽管它看起来合乎逻辑。这个开箱即用的解决方案和 $.cookie 插件非常方便。
  • 在带有 data-toggle="tab" 的标签上应用 .tab() 而不是删除和添加类,另请参阅:stackoverflow.com/questions/16808205/…
  • 对于我的布局,因为我对 div 使用了“淡入活动”,需要更改最后两行以添加或删除“活动中”。
【解决方案3】:

所有其他答案都是正确的。该答案将考虑到同一页面上可能有多个ul.nav.nav-pillsul.nav.nav-tabs 的事实。在这种情况下,之前的答案将失败。

仍然使用localStorage,但使用字符串化的JSON 作为值。代码如下:

$(function() {
  var json, tabsState;
  $('a[data-toggle="pill"], a[data-toggle="tab"]').on('shown', function(e) {
    var href, json, parentId, tabsState;

    tabsState = localStorage.getItem("tabs-state");
    json = JSON.parse(tabsState || "{}");
    parentId = $(e.target).parents("ul.nav.nav-pills, ul.nav.nav-tabs").attr("id");
    href = $(e.target).attr('href');
    json[parentId] = href;

    return localStorage.setItem("tabs-state", JSON.stringify(json));
  });

  tabsState = localStorage.getItem("tabs-state");
  json = JSON.parse(tabsState || "{}");

  $.each(json, function(containerId, href) {
    return $("#" + containerId + " a[href=" + href + "]").tab('show');
  });

  $("ul.nav.nav-pills, ul.nav.nav-tabs").each(function() {
    var $this = $(this);
    if (!json[$this.attr("id")]) {
      return $this.find("a[data-toggle=tab]:first, a[data-toggle=pill]:first").tab("show");
    }
  });
});

这个位可以在整个应用程序的所有页面上使用,并且适用于标签和药片。 另外,请确保标签或药丸默认不处于活动状态,否则您会在页面加载时看到闪烁效果。

重要提示:确保父 ul 有一个 id。谢谢阿兰

【讨论】:

  • 另外,对于 BS3,将 'shown' 事件替换为 'shown.bs.tab'
【解决方案4】:

为了获得最佳选择,请使用以下技术:

$(function() { 
  //for bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line
  $('a[data-toggle="tab"]').on('click', function (e) {
    //save the latest tab; use cookies if you like 'em better:
    localStorage.setItem('lastTab', $(e.target).attr('href'));
  });

  //go to the latest tab, if it exists:
  var lastTab = localStorage.getItem('lastTab');

  if (lastTab) {
    $('a[href="'+lastTab+'"]').click();
  }
});

【讨论】:

    【解决方案5】:

    我更喜欢将选定的选项卡存储在窗口的哈希值中。这也可以将链接发送给同事,他们不会看到“相同”的页面。诀窍是在选择另一个选项卡时更改位置的哈希值。如果您已经在页面中使用 #,则可能必须拆分井号标签。在我的应用中,我使用“:”作为哈希值分隔符。

    <ul class="nav nav-tabs" id="myTab">
        <li class="active"><a href="#home">Home</a></li>
        <li><a href="#profile">Profile</a></li>
        <li><a href="#messages">Messages</a></li>
        <li><a href="#settings">Settings</a></li>
    </ul>
    
    <div class="tab-content">
        <div class="tab-pane active" id="home">home</div>
        <div class="tab-pane" id="profile">profile</div>
        <div class="tab-pane" id="messages">messages</div>
        <div class="tab-pane" id="settings">settings</div>
    </div>
    
    <script>
        $('#myTab a').click(function (e) {
            e.preventDefault()
            $(this).tab('show')
        });
    
        // store the currently selected tab in the hash value
        $("ul.nav-tabs > li > a").on("shown.bs.tab", function (e) {
            var id = $(e.target).attr("href").substr(1);
            window.location.hash = id;
        });
    
        // on load of the page: switch to the currently selected tab
        var hash = window.location.hash;
        $('#myTab a[href="' + hash + '"]').tab('show');
    </script>
    

    【讨论】:

    • 感谢您的回答。它对我来说很好用,我不想仅仅为了这个问题而处理 cookie,所以它很棒。
    • @koppor ,这在回发事件中不起作用。我添加了链接按钮&lt;asp:LinkButton CssClass="form-search" ID="LinkButtonSearch" runat="server"&gt;Search&lt;/asp:LinkButton&gt; ,点击按钮后,它是默认选项卡,而不是当前选项卡。我该如何解决??
    【解决方案6】:

    为了防止页面在第一个选项卡上闪烁,然后在 cookie 保存的选项卡上闪烁(当您在第一个选项卡中确定默认为“活动”类时会发生这种情况)

    删除选项卡和窗格的“活动”类,例如:

    <ul class="nav nav-tabs">
    <div id="p1" class="tab-pane">
    

    把下面的脚本设置成默认的第一个选项卡(需要 jQuery cookie 插件)

        $(function() { 
            $('a[data-toggle="tab"]').on('shown', function(e){
                //save the latest tab using a cookie:
                $.cookie('last_tab', $(e.target).attr('href'));
            });
            //activate latest tab, if it exists:
            var lastTab = $.cookie('last_tab');
            if (lastTab) {
                $('a[href=' + lastTab + ']').tab('show');
            }
            else
            {
                // Set the first tab if cookie do not exist
                $('a[data-toggle="tab"]:first').tab('show');
            }
        });
    

    【讨论】:

      【解决方案7】:

      我在多个页面中有标签,localStorage 也保留了前一页的 lastTab,所以对于下一页,由于它有前一页的 lastTab 在存储中,它在这里没有找到任何匹配的标签,所以没有显示任何内容。我是这样修改的。

      $(document).ready(function(){
          //console.log($('a[data-toggle="tab"]:first').tab('show'))
          $('a[data-toggle="tab"]').on('shown.bs.tab', function () {
              //save the latest tab; use cookies if you like 'em better:
              localStorage.setItem('lastTab', $(this).attr('href'));
          });
      
          //go to the latest tab, if it exists:
          var lastTab = localStorage.getItem('lastTab');
          if ($('a[href=' + lastTab + ']').length > 0) {
              $('a[href=' + lastTab + ']').tab('show');
          }
          else
          {
              // Set the first tab if cookie do not exist
              $('a[data-toggle="tab"]:first').tab('show');
          }
      })
      

      编辑:我注意到我必须为不同的页面使用不同的lastTab 变量名称,否则它们总是会相互覆盖。例如lastTab_klantenlastTab_bestellingen 等用于两个不同的页面 klantenbestellingen 都在选项卡中显示数据。

      $(document).ready(function(){
          //console.log($('a[data-toggle="tab"]:first').tab('show'))
          $('a[data-toggle="tab"]').on('shown.bs.tab', function () {
              //save the latest tab; use cookies if you like 'em better:
              localStorage.setItem('lastTab_klanten', $(this).attr('href'));
          });
      
          //go to the latest tab, if it exists:
          var lastTab_klanten = localStorage.getItem('lastTab_klanten');
          if (lastTab_klanten) {
              $('a[href=' + lastTab_klanten + ']').tab('show');
          }
          else
          {
              // Set the first tab if cookie do not exist
              $('a[data-toggle="tab"]:first').tab('show');
          }
      })
      

      【讨论】:

        【解决方案8】:

        想要褪色效果? @Oktav 代码的更新版本:

        1. 对于 Bootstrap 3
        2. 在 li 和 tab 的 div 上设置类以使淡入淡出正常工作。请注意,所有内容 div 都需要class="tab-pane fade"

        代码:

        // See http://stackoverflow.com/a/16984739/64904
        // Updated by Larry to setup for fading
        $(function() {
          var json, tabsState;
          $('a[data-toggle="pill"], a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
            var href, json, parentId, tabsState;
            tabsState = localStorage.getItem("tabs-state");
            json = JSON.parse(tabsState || "{}");
            parentId = $(e.target).parents("ul.nav.nav-pills, ul.nav.nav-tabs").attr("id");
            href = $(e.target).attr('href');
            json[parentId] = href;
            return localStorage.setItem("tabs-state", JSON.stringify(json));
          });
          tabsState = localStorage.getItem("tabs-state");
          json = JSON.parse(tabsState || "{}");
          $.each(json, function(containerId, href) {
            var a_el = $("#" + containerId + " a[href=" + href + "]");
            $(a_el).parent().addClass("active");
            $(href).addClass("active in");
            return $(a_el).tab('show');
          });
          $("ul.nav.nav-pills, ul.nav.nav-tabs").each(function() {
            var $this = $(this);
            if (!json[$this.attr("id")]) {
              var a_el = $this.find("a[data-toggle=tab]:first, a[data-toggle=pill]:first"),
                  href = $(a_el).attr('href');
              $(a_el).parent().addClass("active");
              $(href).addClass("active in");
              return $(a_el).tab("show");
            }
          });
        });
        

        【讨论】:

          【解决方案9】:

          我让它使用与@dgabriel类似的解决方案,在这种情况下,链接&lt;a&gt;不需要id,它根据位置识别当前标签。

          $(function() { 
            $('a[data-toggle="tab"]').on('shown', function (e) {
              var indexTab = $('a[data-toggle="tab"]').index($(this)); // this: current tab anchor
              localStorage.setItem('lastVisitedTabIndex', indexTab);
            });
          
            //go to the latest tab, if it exists:
            var lastIndexTab  = localStorage.getItem('lastVisitedTabIndex');
            if (lastIndexTab) {
                $('a[data-toggle="tab"]:eq(' + lastIndexTab + ')').tab('show');
            }
          });
          

          【讨论】:

          • 我认为你的代码在 getItem 应该在显示之前是错误的,也解决了两次声明 indexTab 的问题。
          • @JohnMagnolia 我将indexTab 命名了两次,但有区别。指数。所以我会打电话给第二个lastIndexTab。关于shown,这是一个事件,所以在你打开标签之前它不会触发,所以在getItem之前没有关系。
          【解决方案10】:

          我建议进行以下更改

          1. 使用像amplify.store 这样的插件,它提供了一个 具有内置后备功能的跨浏览器/跨平台本地存储 API。

          2. $('#div a[data-toggle="tab"]')等需要保存的标签为目标,以便将此功能扩展到同一页面上存在的多个标签容器。

          3. 使用唯一标识符 (url ??) 跨多个页面保存和恢复上次使用的选项卡。


          $(function() { 
            $('#div a[data-toggle="tab"]').on('shown', function (e) {
              amplify.store(window.location.hostname+'last_used_tab', $(this).attr('href'));
            });
          
            var lastTab = amplify.store(window.location.hostname+'last_used_tab');
            if (lastTab) {
              $("#div a[href="+ lastTab +"]").tab('show');
            }
          });
          

          【讨论】:

            【解决方案11】:

            没有本地存储的简单解决方案:

            $(".nav-tabs a").on("click", function() {
                location.hash = $(this).attr("href");
            });
            

            【讨论】:

              【解决方案12】:

              服务器端方法。确保所有 html 元素都有 class="" 以防未指定,否则您将需要处理空值。

                  private void ActiveTab(HtmlGenericControl activeContent, HtmlGenericControl activeTabStrip)
                  {
                      if (activeContent != null && activeTabStrip != null)
                      {
                          // Remove active from content
                          Content1.Attributes["class"] = Content1.Attributes["class"].Replace("active", "");
                          Content2.Attributes["class"] = Content2.Attributes["class"].Replace("active", "");
                          Content3.Attributes["class"] = Content3.Attributes["class"].Replace("active", "");
              
                          // Remove active from tab strip
                          tabStrip1.Attributes["class"] = tabStrip1.Attributes["class"].Replace("active", "");
                          tabStrip2.Attributes["class"] = tabStrip2.Attributes["class"].Replace("active", "");
                          tabStrip3.Attributes["class"] = tabStrip3.Attributes["class"].Replace("active", "");
              
                          // Set only active
                          activeContent.Attributes["class"] = activeContent.Attributes["class"] + " active";
                          activeTabStrip.Attributes["class"] = activeTabStrip.Attributes["class"] + " active";
                      }
                  }
              

              【讨论】:

                【解决方案13】:

                如果您想在第一次进入页面时显示第一个选项卡,请使用以下代码:

                    <script type="text/javascript">
                        function invokeMeMaster() {
                        var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';
                            if (chkPostBack == 'false') {
                                $(function () {
                                    // for bootstrap 3 use 'shown.bs.tab', for bootstrap 2 use 'shown' in the next line
                                    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                                        // save the latest tab; use cookies if you like 'em better:
                                        localStorage.setItem('lastTab', $(this).attr('href'));
                                    });
                
                                });
                            }
                            else {
                                $(function () {
                
                                    // for bootstrap 3 use 'shown.bs.tab', for bootstrap 2 use 'shown' in the next line
                                    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                                        // save the latest tab; use cookies if you like 'em better:
                                        localStorage.setItem('lastTab', $(this).attr('href'));
                                    });
                
                                    // go to the latest tab, if it exists:
                                    var lastTab = localStorage.getItem('lastTab');
                                    if (lastTab) {
                                        $('[href="' + lastTab + '"]').tab('show');
                                    }
                
                                });
                
                            }
                        }
                        window.onload = function() { invokeMeMaster(); };
                
                    </script>

                【讨论】:

                  【解决方案14】:

                  这是我制作的一个 sn-p,它适用于 Bootstrap 3jQuery 以及 包含不同选项卡的不同 URL虽然它不支持每页有多个标签,但如果您需要该功能,它应该很容易修改。

                  /**
                   * Handles 'Bootstrap' package.
                   *
                   * @namespace bootstrap_
                   */
                  
                  /**
                   * @var {String}
                   */
                  var bootstrap_uri_to_tab_key = 'bootstrap_uri_to_tab';
                  
                  /**
                   * @return {String}
                   */
                  function bootstrap_get_uri()
                  {
                      return window.location.href;
                  }
                  
                  /**
                   * @return {Object}
                   */
                  function bootstrap_load_tab_data()
                  {
                      var uriToTab = localStorage.getItem(bootstrap_uri_to_tab_key);
                      if (uriToTab) {
                      try {
                          uriToTab = JSON.parse(uriToTab);
                          if (typeof uriToTab != 'object') {
                          uriToTab = {};
                          }
                      } catch (err) {
                          uriToTab = {};
                      }
                      } else {
                      uriToTab = {};
                      }
                      return uriToTab;
                  }
                  
                  /**
                   * @param {Object} data
                   */
                  function bootstrap_save_tab_data(data)
                  {
                      localStorage.setItem(bootstrap_uri_to_tab_key, JSON.stringify(data));
                  }
                  
                  /**
                   * @param {String} href
                   */
                  function bootstrap_save_tab(href)
                  {
                      var uri = bootstrap_get_uri();
                      var uriToTab = bootstrap_load_tab_data();
                      uriToTab[uri] = href;
                      bootstrap_save_tab_data(uriToTab);
                  }
                  
                  /**
                   *
                   */
                  function bootstrap_restore_tab()
                  {
                      var uri = bootstrap_get_uri();
                      var uriToTab = bootstrap_load_tab_data();
                      if (uriToTab.hasOwnProperty(uri) &&
                      $('[href="' + uriToTab[uri] + '"]').length) {
                      } else {
                      uriToTab[uri] = $('a[data-toggle="tab"]:first').attr('href');
                      }
                      if (uriToTab[uri]) {
                          $('[href="' + uriToTab[uri] + '"]').tab('show');
                      }
                  }
                  
                  $(document).ready(function() {
                  
                      if ($('.nav-tabs').length) {
                  
                      // for bootstrap 3 use 'shown.bs.tab', for bootstrap 2 use 'shown' in the next line
                      $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                          bootstrap_save_tab($(this).attr('href'));
                      });
                      bootstrap_restore_tab();
                  
                      }
                  
                  });
                  

                  【讨论】:

                    【解决方案15】:

                    $(document).ready(function () {

                            if (JSON.parse(localStorage.getItem('currentClass')) == "active")
                            {
                                jQuery('#supporttbl').addClass('active')
                                $('.sub-menu').css({ "display": "block" });
                            }
                    
                            $("#supporttbl").click(function () { 
                                var currentClass;
                                if ($(this).attr('class')== "active") { 
                    
                                    currentClass = $(this).attr('class');
                    
                                    localStorage.setItem('currentClass', JSON.stringify(currentClass));
                                    console.log(JSON.parse(localStorage.getItem('currentClass')));
                    
                                    jQuery('#supporttbl').addClass('active')
                                    $('.sub-menu').css({ "display": "block" });
                    
                                } else {
                    
                                    currentClass = "Null"; 
                    
                                    localStorage.setItem('currentClass', JSON.stringify(currentClass));
                                    console.log(JSON.parse(localStorage.getItem('currentClass')));
                    
                                    jQuery('#supporttbl').removeClass('active')
                                    $('.sub-menu').css({ "display": "none" });
                    
                                }  
                            });
                    

                    });

                    【讨论】:

                      【解决方案16】:

                      如果页面中有多个标签,可以使用以下代码

                      <script type="text/javascript">
                      $(document).ready(function(){
                          $('#profileTabs').on('show.bs.tab', function(e) {
                              localStorage.setItem('profileactiveTab', $(e.target).attr('href'));
                          });
                          var profileactiveTab = localStorage.getItem('profileactiveTab');
                          if(profileactiveTab){
                              $('#profileTabs a[href="' + profileactiveTab + '"]').tab('show');        
                          }
                          $('#charts-tab').on('show.bs.tab', function(e) {
                              localStorage.setItem('chartsactiveTab', $(e.target).attr('href'));
                          });
                          var chartsactiveTab = localStorage.getItem('chartsactiveTab');
                          if(chartsactiveTab){
                              $('#charts-tab a[href="' + chartsactiveTab + '"]').tab('show');        
                          }     
                      });
                      </script>
                      

                      【讨论】:

                        【解决方案17】:

                        这将刷新选项卡,但仅在控制器中的所有内容都加载后。

                        // >= angular 1.6 angular.element(function () {
                        angular.element(document).ready(function () {
                            //Here your view content is fully loaded !!
                            $('li[href="' + location.hash + '"] a').tab('show');
                        });
                        

                        【讨论】:

                          【解决方案18】:

                          我将它与 MVC 一起使用:

                          • 模型中有一个 SelectedTab 整数字段,用于将值发送到 POST 方法

                          JavaScript 部分:

                          <script type="text/javascript">
                              $(document).ready(function () {
                                 var index = $("input#SelectedTab").val();
                                 $("#tabstrip > ul li:eq(" + index + ")").addClass("k-state-active");
                          
                                 $("#tabstrip").kendoTabStrip();
                              });
                              function setTab(index) {
                                $("input#SelectedTab").val(index)
                              }
                          </script>
                          

                          HTML 部分:

                          @using (Html.BeginForm())
                          {
                          @Html.AntiForgeryToken()
                          @Html.HiddenFor(model => model.SelectedTab)
                          <div id="tabstrip">
                              <ul>
                                  <li onclick="setTab(0)">Content 0</li>
                                  <li onclick="setTab(1)">Content 1</li>
                                  <li onclick="setTab(2)">Content 2</li>
                                  <li onclick="setTab(3)">Content 3</li>
                                  <li onclick="setTab(4)">Content 4</li>
                              </ul>
                              <div>
                          
                              </div>
                              <div>
                          
                              </div>
                              <div>
                          
                              </div>
                              <div>
                          
                              </div>
                              <div>
                          
                              </div>
                          </div>
                          <div class="content">
                              <button type="submit" name="save" class="btn bg-blue">Save</button>
                          </div>
                          }
                          

                          【讨论】:

                            猜你喜欢
                            • 2017-01-20
                            • 2023-01-25
                            • 2013-05-24
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            相关资源
                            最近更新 更多