jQuery 记住刷新后哪个选项卡处于活动状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4299435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:02:06  来源:igfitidea点击:

Remember which tab was active after refresh

jqueryjquery-plugins

提问by thegunner

I'm using jquery tabs on a web page and when the page is refreshed it loses what ever tab I had been on and goes back to the first tab.

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

Has anyone come across this problem and know how to solve it?

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

采纳答案by tawfekov

I assume that you are using jQuery UI tabs ,

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

here is an example of using tabs + cookies to save the last clicked tab

这是使用选项卡 + cookie 保存上次单击的选项卡的示例

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

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

demo : open this link http://jqueryui.com/demos/tabs/cookie.html

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

the close it and re open it and you will see the same clicked tab

关闭它并重新打开它,您将看到相同的点击选项卡

update:after 3 years of this answer jquery ui has deprecated the cookie option : http://jqueryui.com/upgrade-guide/1.9/#deprecated-cookie-option.

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

but you can still append take a look here if this fits your needs or not https://stackoverflow.com/a/14313315/109217

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

回答by Arik

Like others I was struggling with my ui-tabs cookie history in jQueryUI 1.10. Thanks to Harry's solution and some other online documentation I refer to in the code below I now have a working non-cookie solution! I was able to test in Firefox 18.0.1 and IE 9.0.12. According to my resources, Chrome, Firefox, Safari and IE8 & above support Session Storage.

像其他人一样,我在 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 ) 
        }
    }); 
    }); 

回答by Hatcham

A simpler alternative I have just implemented:

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

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

That will add the hash value to the url so a page refresh will reload that tab, and by using location.replacerather than location.hash, we don't fill the user's history up with unwanted steps back.

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

Hope that helps.

希望有帮助。

回答by Harry

Now that cookie is gone in jQuery UI 1.10.0, I mixed Gayathiri's approach with the new options and events:

现在 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 });
    }
});

回答by dsgriffin

Short, layout-independent way of doing this using localStorage:

使用localStorage执行此操作的简短、独立于布局的方法:

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


A layout-specific way of doing it using custom data attributes (possibly useful if the attribute values were to be used in some way elsewhere in your script).

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

jQuery UI:

jQuery 用户界面:

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

Example HTML layout:

示例 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>

回答by Orbling

When web pages refresh, they reload their state from the server, by requesting the page again.

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

Either the webserver needs to remember the state and supply the file differently than the default, or you may be able to use cookies or the hash-component of the URL and some jQuery to store the state, read it on load and restore it.

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

See the jquery.cookie pluginor SWFaddress, learn about manipulating hash values yourself or the jQuery History plugin.

请参阅jquery.cookie插件SWFaddress,了解自己或 jQuery History 插件如何操作哈希值。

The hash method has a particular attraction as it replicates changes of URL, so copy/paste of the URL still works, as do bookmarks.

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

回答by ManuEl Magak

If you're using bootstrap 3 or 4 tabs, you could use local storage to store the current tab id then set it to show on page load. First you'll prevent the default method to open the tab, then save the opened tab link id on tab open event.

如果您使用引导程序 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');
    }

Always works fine for me.

对我来说总是很好。

回答by Maurizio In denmark

Another option is to use html 5 storage. See here for an example: http://www.w3schools.com/html/html5_webstorage.asp

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

回答by Jeff

Here is an alternative way to allow remembering the open tab by the element id (not index). This is useful, if you use this code to synchronize the open tabs on two different pages with similar elements (like show and edit page).

这是允许通过元素 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'));
   }
});

Works with jQuery UI 1.10. Do not forget to include the jquery.cookie plugin!

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

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

回答by Poppy

Include the jquery cookies plugin :

包括 jquery cookie 插件:

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

declare a cookie name inside $.function({.. or document.ready as

在 $.function({.. or document.ready as

var cookieName = "mycookie";

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