刷新后记住哪个选项卡是活动的

55

我在网页上使用jQuery标签页,但是当页面刷新时,它会丢失我所在的标签页并返回到第一个标签页。

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


Cookies是你的好朋友。 - Alex
17个回答

40

和其他人一样,我在jQueryUI 1.10中苦苦挣扎着想要解决我的ui-tabs cookie历史记录问题。多亏了Harry的解决方案以及下面代码中我参考的其他在线文档,现在我有了一个可行的非cookie解决方案!我已经在Firefox 18.0.1和IE 9.0.12中进行了测试。根据我的资源,Chrome、Firefox、Safari和IE8及以上版本都支持会话存储。

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

2
迄今为止最好的方法,我只是想向新的jQuery用户指出一件事:'$(function(){ }'这一行与'$(document).ready(function(){ }'行是相同的,它意味着您提供的代码在页面每次进入时都会执行,但在DOM完全加载后执行。 - netfed
不错!可以与jQuery UI 1.8.20一起使用。 - Ben Power
使用marcuswestin的store.js可以更好地工作: https://github.com/marcuswestin/store.js/ - Charles Byrne
天啊,这是一些文档级别的东西...你应该看看我们的生产代码,哈哈。 - Dave Lawrence
有效的解决方案。虽然如果能整理成可重复使用、易于操作的解决方案,避免每次代码混乱会更好。 - Jodes
对我来说完美地工作了。谢谢! - Tom Johnson

21

我假设您正在使用jQuery UI选项卡,

以下是使用选项卡+ cookie保存最后点击的选项卡的示例

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://dev59.com/MmYq5IYBdhLWcg3wpyNE#14313315


3
链接已失效。我认为另一个链接可能不再显示您想要的内容。也许我错了...? - Rick Smith
@RickSmith 这个回答已经有3年了,无论如何我现在将会更新它。 - tawfekov
3
@tawfekov 还是一个链接答案。 - kelunik
1
感谢您的更新以保持其相关性。 - ChrisSwires

11

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

$(".tabs").tabs({
    select: function(event, ui) {                   
       window.location.replace(ui.tab.hash);
    },
});
那会将哈希值添加到URL中,因此在页面刷新时将重新加载该选项卡,通过使用location.replace而不是location.hash,我们不会填充用户历史记录中的不需要的步骤。 希望这有所帮助。

3
你的方法很棒,但是重新加载了页面。使用"window.location.hash = ui.tab.hash;"可以在不重新加载页面的情况下完成同样的工作。 - jlfenaux

5

既然在jQuery UI 1.10.0中cookie已经被移除,我将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+,这似乎是最佳解决方案。 - javram
当我按照上面的评论建议删除了我的解决方案中的“路径”时,它运行得非常好。 - Glenn

4
使用localStorage实现这一点的简短、与布局无关的方法: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>

3
如果你正在使用Bootstrap 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');
    }

对我来说总是很好用。


2
当网页刷新时,它们会通过再次请求页面来从服务器重新加载其状态。
要么Web服务器需要记住状态并以不同于默认方式提供文件,要么您可以使用Cookie或URL的哈希组件和一些jQuery来存储状态,在加载时读取并恢复它。
请查看jquery.cookie插件SWFaddress,了解如何自己操作哈希值或使用jQuery History插件。
哈希方法具有特定的吸引力,因为它复制了URL的更改,因此复制/粘贴URL仍然有效,书签也有效。

1

1

包含jquery cookies插件:

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

在$.function({..或document.ready中声明一个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), selected -> active, select -> activate, ui.index -> ui.newTab.index()。 - Rick Smith
很抱歉,我不明白这个函数实际上是做什么的? - May

1
你可以尝试这样做,非常容易。
# 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接