문제

I have a screen that uses jQuery tabs and was wondering if somehow I can keep the selected tab after a refresh of the page (JS .reload();)?

Any guidance appreciated.

도움이 되었습니까?

해결책

https://github.com/carhartl/jquery-cookie

or

http://code.google.com/p/cookies/downloads/detail?name=jquery.cookies.2.2.0.js.zip&can=2&q=

Example for jquery.cookies.2.2.0.js

$(document).ready(function () {
   var initialTabIndex = 0;
   var jCookies = jQuery.cookies;

   //alert('getting ' + jCookies.get("currentTab"));

   if(jCookies.get("currentTab") != null){
      initialTabIndex = jCookies.get("currentTab");
   }

   $('#tabs').tabs({
      activate : function(e, ui) {
         //alert('setting ' + ui.newTab.index());
         jCookies.set("currentTab", ui.newTab.index().toString());
      },
      active : initialTabIndex
   });
});

다른 팁

While the previous answer using cookies will certainly work, it is probably not the ideal solution given peoples aversions to accepting cookies. (it also means you would need to show a disclaimer on your site stating you use cookies, at least to EU visitors). I'd recommend avoiding using cookies where possible so your site remains functional if cookies are disabled/rejected.

A better way is to use the "hash" on the end of a URL.

Modify your tab links as follows:

<div id="UITabs">
<ul>
    <li><a href="#Tab1">Tab 1</a></li>
    <li><a href="#Tab2">Tab 2</a></li>
    <li><a href="#Tab3">Tab 3</a></li>
</ul>
<div id="Tab1"></div>
<div id="Tab2"></div>
<div id="Tab3"></div>
</div>

Then in your head, add the following javascript to ensure the hash is set when changing tabs, and get the hash on pageload and display the required tab:

$(document).ready(function () {

    $(function () {
        $("#UITabs").tabs();

        $("#UITabs").bind("tabsshow", function (event, ui) {
            location.hash = ui.newTab.find('a.ui-tabs-anchor').attr('href');
        });

        $(window).bind('hashchange', function (e) {
            $("#UITabs").tabs("select", location.hash);
        });
    });
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top