【问题标题】:Remember which tab was active after refresh记住刷新后哪个选项卡处于活动状态
【发布时间】:2025-12-25 12:50:06
【问题描述】:

我在网页上使用 jquery 选项卡,当页面刷新时,它会丢失我之前所在的选项卡并返回到第一个选项卡。

有没有人遇到过这个问题并知道如何解决?

【问题讨论】:

  • Cookie 是你的朋友。

标签: jquery jquery-plugins


【解决方案1】:

您可以使用jQuery History plugin,这里是demo(在演示中加载另一个链接并尝试刷新)

【讨论】:

    【解决方案2】:

    当网页刷新时,它们会通过再次请求页面从服务器重新加载其状态。

    要么网络服务器需要记住状态并以不同于默认的方式提供文件,要么您可以使用 cookie 或 URL 的哈希组件和一些 jQuery 来存储状态,在加载时读取并恢复它。

    查看jquery.cookie pluginSWFaddress,了解如何自己操作哈希值或 jQuery History 插件。

    哈希方法具有特殊的吸引力,因为它复制了 URL 的更改,因此 URL 的复制/粘贴仍然有效,书签也是如此。

    【讨论】:

      【解决方案3】:

      我假设您使用的是 jQuery UI 选项卡,

      这里是一个使用 tabs + cookies 来保存最后点击的 tab 的例子

      http://jqueryui.com/demos/tabs/#cookie

      演示: 打开这个链接 http://jqueryui.com/demos/tabs/cookie.html

      关闭它并重新打开它,您将看到相同的点击标签

      更新: 在得到这个答案 3 年后,jquery ui 已弃用 cookie 选项:http://jqueryui.com/upgrade-guide/1.9/#deprecated-cookie-option

      但如果这符合您的需要,您仍然可以在此处附加查看https://*.com/a/14313315/109217

      【讨论】:

      • jqueryui.com/demos/tabs/cookie.html 链接已损坏。我认为另一个链接不再显示您想要的内容。也许我弄错了……?
      • @RickSmith 这个答案已经 3 岁了,无论如何我现在都会更新它
      • @tawfekov 它仍然是一个链接答案。
      • 感谢您更新以保持相关性。
      【解决方案4】:

      我的公司阻止了 cookie,因此我找到了解决方法。只需使用隐藏字段跟踪选项卡,并在请求完成后将该值传回。它不漂亮,但它完成了工作。

      <% if(request.getAttribute("tab")==null) { %>
          $("#tabs").tabs();
      <% } else { %>
          $("#tabs").tabs({selected:<%=request.getAttribute("tab").toString() %>});
      <% } %>
      

      在后端我只是设置了属性

      request.setAttribute("tab", f.get("tab").toString());
      

      希望这会有所帮助。

      【讨论】:

        【解决方案5】:

        我刚刚实现的一个更简单的替代方案:

        $(".tabs").tabs({
            select: function(event, ui) {                   
               window.location.replace(ui.tab.hash);
            },
        });
        

        这会将哈希值添加到 url,因此页面刷新将重新加载该选项卡,并且通过使用 location.replace 而不是 location.hash,我们不会在用户的历史记录中添加不需要的步骤。

        希望对您有所帮助。

        【讨论】:

        • 您的方法很棒,但会重新加载页面。 window.location.hash = ui.tab.hash;无需重新加载页面即可完成相同的工作。
        【解决方案6】:

        你认为你可以在下面的代码中添加相同的功能吗?

        $(".menu > li").click(function(e){
            $(".content." + $(".menu > .active").attr("id")).fadeOut("fast", function() {
                $(".content." + e.target.id).fadeIn();
                $(".menu > #" + e.target.id).addClass("active");
            });
        
            $(".menu > .active").removeClass("active");
        
            return true;
        
        });
        

        【讨论】:

        • 您的代码看起来不错(即使没有正确缩进),但请考虑解释一下它将如何提供帮助!
        【解决方案7】:

        包含 jquery cookies 插件:

        <script type="text/javascript" src="/resources/js/jquery.cookies.2.2.0.min.js"></script>
        

        在 $.function({.. 或 document.ready as 中声明一个 cookie 名称

        var cookieName = "mycookie";
        
        $("#tabs").tabs({
            selected : ($.cookies.get(cookieName) || 0),
            select : function(e, ui) {
                $.cookies.set(cookieName, ui.index);
            }
                });
        

        【讨论】:

        • 较新的版本应该进行以下更改: $.cookies.get(cookieName) -> $.cookie(cookieName), $.cookies.set(cookieName) -> $.cookie(cookieName, value ), 选中 -> 激活, 选择 -> 激活, ui.index -> ui.newTab.index(),
        • 很抱歉,我不明白这个函数到底是做什么的?
        【解决方案8】:

        你可以试试这样的,很容易做到的。

        # Set selected_tab to the correct index based on the current url anchor hash
        selected_tab = 0
        if matches = /#(\w+)/.exec(window.location.hash)
          # find the index of the tab with the given id
          selected_tab = $('#' + matches[1]).index() - 1
        
        # Initialize the tabs and set 'selected' to equal the selected_tab variable we just set
        $('.tabable').tabs
          selected: selected_tab,  # this is where the magic happens
          select: (evt, ui) ->
            window.location.hash = ui.panel.id  # set an anchor tag in the url with the tab id
        

        【讨论】:

          【解决方案9】:

          现在 cookie 在 jQuery UI 1.10.0 中消失了,我将 Gayathiri 的方法与新的选项和事件混合在一起:

          // using cookie plugin from https://github.com/carhartl/jquery-cookie
          
          var tabCookieName = "ui-tabs-1";
          $(".tabs").tabs({
              active : ($.cookie(tabCookieName) || 0);
              activate : function( event, ui ) {
                  var newIndex = ui.newTab.parent().children().index(ui.newTab);
                  // my setup requires the custom path, yours may not
                  $.cookie(tabCookieName, newIndex, { path: window.location.pathname });
              }
          });
          

          【讨论】:

          • 如果使用 1.10+,这似乎是最好的解决方案
          • 正如上面的评论所暗示的,当我的解决方案的“路径”被删除时效果很好。
          【解决方案10】:

          像其他人一样,我在 jQueryUI 1.10 中为我的 ui-tabs cookie 历史而苦苦挣扎。 感谢 Harry 的解决方案和我在下面的代码中引用的其他一些在线文档,我现在有了一个有效的非 cookie 解决方案!我能够在 Firefox 18.0.1 和 IE 9.0.12 中进行测试。根据我的资源,Chrome、Firefox、Safari和IE8及以上都支持Session Storage。

            $(function() {
              //  jQueryUI 1.10 and HTML5 ready
              //      http://jqueryui.com/upgrade-guide/1.10/#removed-cookie-option 
              //  Documentation
              //      http://api.jqueryui.com/tabs/#option-active
              //      http://api.jqueryui.com/tabs/#event-activate
              //      http://balaarjunan.wordpress.com/2010/11/10/html5-session-storage-key-things-to-consider/
              //
              //  Define friendly index name
              var index = 'key';
              //  Define friendly data store name
              var dataStore = window.sessionStorage;
              //  Start magic!
              try {
                  // getter: Fetch previous value
                  var oldIndex = dataStore.getItem(index);
              } catch(e) {
                  // getter: Always default to first tab in error state
                  var oldIndex = 0;
              }
              $('#tabs').tabs({
                  // The zero-based index of the panel that is active (open)
                  active : oldIndex,
                  // Triggered after a tab has been activated
                  activate : function( event, ui ){
                      //  Get future value
                      var newIndex = ui.newTab.parent().children().index(ui.newTab);
                      //  Set future value
                      dataStore.setItem( index, newIndex ) 
                  }
              }); 
              }); 
          

          【讨论】:

          • 迄今为止最好的方法,我只是想向新的 Jquery 用户说明一些问题:'$(function() {' 行与 '$(document) .ready(function () {' 行,表示你提供的代码每次进入页面都会执行,但是在DOM完全加载之后。
          • 不错!适用于 jquery ui 1.8.20。
          • 使用来自 marcuswestin 的 store.js 效果更好:github.com/marcuswestin/store.js
          • 天哪,这是某种级别的文档...您应该看到我们的生产代码哈哈
          • 有效的解决方案。虽然如果能把它整理成一个可重用的、糖衣的解决方案,以避免每次代码混乱,那就太好了
          【解决方案11】:
             $(function () {
          
                  $("#dialog").dialog({
                      autoOpen: false,
                      show: {
                          effect: "blind",
                          duration: 1000
                      },
                      hide: {
                          effect: "explode",
                          duration: 1000
                      }
                  });
          
                  //$(function () {
                      $("#tabs").tabs({
                              select: function (event, ui) {                       
                              document.location.href = ui.tab.href;                        
                          }
                      }).show();
          
                  //});
          
                              $("#MainContent_button1").click(function (event) {                           
                                  event .preventDefault();
                                   $("#dialog").dialog("open");                           
                              });
              });
          

          我在ASP.NET 中使用过它,它对我来说很好用。我在第二个选项卡中也有一个按钮来显示一些对话框,并且效果很好。

          法会

          【讨论】:

            【解决方案12】:

            另一种选择是使用 html 5 存储。示例见此处:http://www.w3schools.com/html/html5_webstorage.asp

            【讨论】:

              【解决方案13】:

              这是允许通过元素 id(而不是索引)记住打开的选项卡的另一种方法。如果您使用此代码同步具有相似元素(如显示和编辑页面)的两个不同页面上的打开选项卡,这很有用。

              var tabsid = "#tabs";
              var cookieid = "tabs_selected2";
              
              var activetabnr = 0;
              if (($.cookie(cookieid)!=null) && ($.cookie(cookieid)!="")) {
                 activetabnr = $(tabsid+' a[href="'+$.cookie(cookieid)+'"]').parent().index();
              }
              
              $(tabsid).tabs({
                 active: $(tabsid).tabs({ active: activetabnr }),
                 beforeActivate: function (event, ui) {
                      $.cookie(cookieid, "#"+ui.newPanel.attr('id'));
                 }
              });
              

              适用于 jQuery UI 1.10。 不要忘记包含jquery.cookie plugin

              <script type="text/javascript" src="/js/jquery.cookie.js"></script>
              

              【讨论】:

                【解决方案14】:

                使用localStorage 的简短、独立于布局的方式:

                $("#tabs").tabs({
                  active: localStorage.getItem("currentIdx"),
                  activate: function(event, ui) {
                      localStorage.setItem("currentIdx", $(this).tabs('option', 'active'));
                  }
                });
                

                一种使用自定义数据属性的特定于布局的方法(如果要在脚本的其他地方以某种方式使用属性值,则可能很有用)。

                jQuery UI:

                $("#tabs").tabs({
                    active: localStorage.getItem("currentTabIndex"),
                    activate: function(event, ui) {
                        localStorage.setItem("currentTabIndex", ui.newPanel[0].dataset["tabIndex"]);
                    }
                });
                

                示例 HTML 布局:

                <div id="tabs">
                    <div id="tabs-1" data-tab-index="0">
                       tab 1 stuff...
                    </div>
                    <div id="tabs-2" data-tab-index="1">
                       tab 2 stuff...
                    </div>    
                    <div id="tabs-3" data-tab-index="2">
                       tab 3 stuff...
                    </div>
                </div>
                

                【讨论】:

                  【解决方案15】:

                  在关注blog 的帮助下,我解决了同样的问题。

                  HTML 标签

                   <ul class="tabs clear-fix">
                       <li class=""><a href="#tab=java" id="tab1-tab"><i class=" fa fa-search-plus fa-lg" style="font-size:16px; "></i>JAVA</a><span></span></li>
                       <li class=""><a href="#tab=js"  id="tab2-tab"><i class=" fa fa-user fa-lg" style="font-size:16px;"></i>JAVA SCRIPT</a><span></span></li>
                       <li><a href="#tab=c"  id="tab3-tab"><i class="fa fa-archive fa-lg" style="font-size:16px;"></i>C</a><span></span></li>
                       <li><a href="#tab=c2"  id="tab4-tab"><i class=" fa fa-gift fa-lg" style="font-size:16px;"></i>C++</a><span></span></li>
                       <li><a href="#tab=jQ"  id="tab5-tab"><i class=" fa fa-heart fa-lg" style="font-size:16px;"></i>jQuery</a><span></span></li>
                      </ul>
                  

                  Javascript

                   var selectedTab =  window.location.href.split("#tab=")[1] ;
                      var selectedId = $('a[href$=' + selectedTab+']:first').attr('id');
                  
                      if (typeof selectedId === "undefined") {
                           $('#tab1-tab').trigger("click");
                      }
                      else{
                          $('#'+selectedId).trigger("click");
                      }
                  

                  对我来说它有效,建议赞赏。

                  【讨论】:

                    【解决方案16】:

                    我最近遇到了同样的问题,并花了很长时间查看JQuery UI Tabs Widget 的文档。我最终使用事件 activatecreate 用于 JQuery UI 1.10 以及 localStorage 在页面刷新之前存储当前选项卡。

                        $( ".selector" ).tabs({                                                 
                            activate: function( event, ui) {
                                //when tab is activated store it's index in activeTabIndex
                                    var activeTabIndex = $('.tabs').tabs('option','active');
                                //add activeTabIndex to localStorage and set with key of 'currentTab'  
                                    localStorage.setItem('currentTab', activeTabIndex); 
                                                },
                                create: function( event, ui ) {
                                    $(".tabs").tabs({       
                                //when tabs are created on page refresh, the active tab is set to index of 'currentTab' 
                                //after getItem from localStorage
                                active: localStorage.getItem('currentTab')
                            });
                          }
                       });
                    

                    【讨论】:

                      【解决方案17】:

                      如果您使用引导程序 3 或 4 个选项卡,则可以使用本地存储来存储当前选项卡 ID,然后将其设置为在页面加载时显示。 首先,您将阻止默认方法打开选项卡,然后在选项卡打开事件中保存打开的选项卡链接 ID。

                       $('a[data-toggle="tab"]').click(function (e) {
                              e.preventDefault();
                              $(this).tab('show');
                          });
                      
                          $('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
                              var id = $(e.target).attr("href");
                              localStorage.setItem('selectedTab', id)
                          });
                      
                          var selectedTab = localStorage.getItem('selectedTab');
                      
                          if (selectedTab != null) {
                              $('a[data-toggle="tab"][href="' + selectedTab + '"]').tab('show');
                          }
                      

                      对我来说总是很好。

                      【讨论】:

                        最近更新 更多