Javascript 页面重新加载后,如何使用 twitter bootstrap 保持当前选项卡处于活动状态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10523433/
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-24 01:42:15  来源:igfitidea点击:

How do I keep the current tab active with twitter bootstrap after a page reload?

javascriptjquerytwitter-bootstrap

提问by Paul

I'm currently using tabs with Twitter Bootstrap and want to select the same tab after a user has posted data and the page reloads.

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

How is this done?

这是怎么做的?

My current call to inti the tabs looks like this:

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

<script type="text/javascript">

$(document).ready(function() {

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

My tabs:

我的标签:

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

回答by dgabriel

You'll have to use localStorage or cookies to manage that. Here's a quick and dirty solution that can be vastly improved, but may give you a starting point:

您必须使用 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');
    }
});

回答by ricsrock

Got this to work using cookies and also removing the 'active' class from any other tabs and tab panes... and adding the 'active' class to the current tab and tab pane.

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

I'm sure there's a better way to do this, but this appears to work in this case.

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

Requires the jQuery cookie plugin.

需要 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');
  }
});

回答by Oktav

All other answers are correct. This answer will take into account the fact that one might have multiple ul.nav.nav-pillsor ul.nav.nav-tabson the same page. In this case, the previous answers will fail.

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

Still using localStoragebut with a stringified JSONas the value. Here is the code:

仍在使用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");
    }
  });
});

This bit can be used on the entire app over all pages and will work for both tabs and pills. Also, make sure the tabs or pills are not active by default, otherwise you will see a flicker effect at page load.

此位可用于所有页面的整个应用程序,并且适用于选项卡和药丸。另外,请确保默认情况下选项卡或药丸未处于活动状态,否则您会在页面加载时看到闪烁效果。

Important: Make sure the parent ulhas an id. Thanks Alain

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

回答by Vaimeo

For the best option, use this technique:

对于最佳选择,请使用以下技术:

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

回答by koppor

I prefer storing the selected tab in the hashvalue of the window. This also enables sending links to colleagues, who than see "the same" page. The trick is to change the hash of the location when another tab is selected. If you already use # in your page, possibly the hash tag has to be split. In my app, I use ":" as hash value separator.

我更喜欢将选定的选项卡存储在窗口的哈希值中。这也允许向看到“相同”页面的同事发送链接。诀窍是在选择另一个选项卡时更改位置的哈希值。如果您已经在页面中使用了 #,则可能需要拆分哈希标签。在我的应用程序中,我使用“:”作为哈希值分隔符。

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

回答by Jeferson Tenorio

To prevent the page flashing on the first tab and then the tab that was saved by the cookie (this occurs when you determine the class "active" by default in the first TAB)

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

Remove the class "active" of tabs and panes like:

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

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

Put the script below to set first tab like default (Requires the jQuery cookie plugin)

将下面的脚本设置为默认的第一个选项卡(需要 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');
        }
    });

回答by Larry K

Want fading effect? Updated version of @Oktav's code:

想要渐变效果?@Oktav 代码的更新版本:

  1. For Bootstrap 3
  2. Sets up the classes on the li and tab's div to enable fading to work properly. Note that all of the content divs need class="tab-pane fade"
  1. 对于 Bootstrap 3
  2. 在 li 和 tab 的 div 上设置类以使淡入淡出正常工作。请注意,所有内容 div 都需要class="tab-pane fade"

Code:

代码:

// 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");
    }
  });
});

回答by GoharSahi

I had tabs in multiple pages and localStorage keeps lastTab from previous pages as well, so for next page, since it had previous page's lastTab in storage, it didn't find any matching tab here, so nothing was being displayed. I modified it this way.

我在多个页面中有标签,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');
    }
})

edit:I've noticed that I'll have to have different lastTabvariable names for different pages, otherwise, they'll always overwrite each other. e.g. lastTab_klanten, lastTab_bestellingenetc. for two different pages klantenand bestellingenboth having data displayed in tabs.

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

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

回答by Jaider

I made it works with similar solution as @dgabriel, in this case, the links <a>don't need id, it identify the current tab based on the position.

我使它与@dgabriel 使用类似的解决方案一起工作,在这种情况下,<a>不需要链接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');
  }
});

回答by Sandeep

I suggest the following changes

我建议进行以下更改

  1. Use a plugin like amplify.storewhich provides a crossbrowser/ crossplatform localstorage API with builtin fallbacks.

  2. Target the tab that needs to be saved like $('#div a[data-toggle="tab"]')so as to extend this functionality to multiple tab containers that exist on the same page.

  3. Use a unique identifier (url ??)to save and restore last used tabs across multiple pages.

  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');
  }
});