Bootstrap 3: Zachowaj zaznaczoną kartę przy odświeżaniu strony

Próbuję utrzymać zaznaczoną kartę aktywną przy odświeżaniu za pomocą Bootstrap 3 . Próbowałem i sprawdzałem z pewnym pytaniem już zadanym tutaj, ale nic nie działa dla mnie. Nie wiem, gdzie się mylę. Oto Mój kod

HTML

<!-- tabs link -->
<ul class="nav nav-tabs" id="rowTab">
    <li class="active"><a href="#personal-info" data-toggle="tab">Personal Information</a></li>
    <li><a href="#Employment-info" data-toggle="tab">Employment Information</a></li>
    <li><a href="#career-path" data-toggle="tab">Career Path</a></li>
    <li><a href="#warnings" data-toggle="tab">Warning</a></li>
</ul>
<!-- end: tabs link -->

<div class="tab-content">
    <div class="tab-pane active" id="personal-info">
        tab data here...
    </div>

    <div class="tab-pane" id="Employment-info">
        tab data here...
    </div>

    <div class="tab-pane" id="career-path">
        tab data here...
    </div>

    <div class="tab-pane" id="warnings">
        tab data here...
    </div>
</div>

Javascript :

// tab
$('#rowTab a:first').tab('show');

//for bootstrap 3 use 'shown.bs.tab' instead of '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('selectedTab', $(e.target).attr('id'));
});

//go to the latest tab, if it exists:
var selectedTab = localStorage.getItem('selectedTab');
if (selectedTab) {
  $('#'+selectedTab).tab('show');
}
Author: devo, 2013-09-25

17 answers

Wolę przechowywać wybraną kartę w hashvalue okna. Umożliwia to również wysyłanie linków do kolegów, którzy widzą "tę samą" stronę. Sztuczka polega na zmianie hasha lokalizacji Po wybraniu innej karty. Jeśli używasz już # na swojej stronie, prawdopodobnie tag hash musi zostać podzielony. W mojej aplikacji używam ": "jako separatora wartości hash.

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

JavaScript, musi być osadzony po powyższym w <script>...</script> części.

$('#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');
 156
Author: koppor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-15 07:37:57

To jest najlepszy, jaki próbowałem:

$(document).ready(function() {
    if (location.hash) {
        $("a[href='" + location.hash + "']").tab("show");
    }
    $(document.body).on("click", "a[data-toggle]", function(event) {
        location.hash = this.getAttribute("href");
    });
});
$(window).on("popstate", function() {
    var anchor = location.hash || $("a[data-toggle='tab']").first().attr("href");
    $("a[href='" + anchor + "']").tab("show");
});
 101
Author: Xavi Martínez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-23 23:13:32

Mieszanka między innymi odpowiedzi:

  • No jump on click
  • Zapisz na miejscu hash
  • Zapisz na localStorage (np: for form submit)
  • Po prostu skopiuj & wklej;)

    if (location.hash) {
      $('a[href=\'' + location.hash + '\']').tab('show');
    }
    var activeTab = localStorage.getItem('activeTab');
    if (activeTab) {
      $('a[href="' + activeTab + '"]').tab('show');
    }
    
    $('body').on('click', 'a[data-toggle=\'tab\']', function (e) {
      e.preventDefault()
      var tab_name = this.getAttribute('href')
      if (history.pushState) {
        history.pushState(null, null, tab_name)
      }
      else {
        location.hash = tab_name
      }
      localStorage.setItem('activeTab', tab_name)
    
      $(this).tab('show');
      return false;
    });
    $(window).on('popstate', function () {
      var anchor = location.hash ||
        $('a[data-toggle=\'tab\']').first().attr('href');
      $('a[href=\'' + anchor + '\']').tab('show');
    });
    
 30
Author: insign,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-04 02:53:37

Kod Xaviego był w pełni sprawny. Ale podczas przechodzenia do innej strony, przesyłanie formularza, a następnie przekierowanie do strony z moimi kartami Nie ładowało zapisanej karty w ogóle.

LocalStorage na ratunek (nieco zmieniony kod Nguyena):

$('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');
}
 13
Author: apfz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-28 06:17:36

Ten używa HTML5 localStorage do przechowywania aktywnej zakładki

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if (activeTab) {
   $('#navtab-container a[href="' + activeTab + '"]').tab('show');
}

Ref: http://www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.php https://www.w3schools.com/bootstrap/bootstrap_ref_js_tab.asp

 8
Author: Ajith R Nair,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-13 06:49:59

Opierając się na odpowiedziach dostarczonych przez Xavi Martínez i koppor } wymyśliłem rozwiązanie, które wykorzystuje url hash lub localStorage w zależności od dostępności tego ostatniego:

function rememberTabSelection(tabPaneSelector, useHash) {
    var key = 'selectedTabFor' + tabPaneSelector;
    if(get(key)) 
        $(tabPaneSelector).find('a[href=' + get(key) + ']').tab('show');

    $(tabPaneSelector).on("click", 'a[data-toggle]', function(event) {
        set(key, this.getAttribute('href'));
    }); 

    function get(key) {
        return useHash ? location.hash: localStorage.getItem(key);
    }

    function set(key, value){
        if(useHash)
            location.hash = value;
        else
            localStorage.setItem(key, value);
    }
}

Użycie:

$(document).ready(function () {
    rememberTabSelection('#rowTab', !localStorage);
    // Do Work...
});

Nie nadąża za tylnym przyciskiem, jak ma to miejsce w przypadku rozwiązania .

 4
Author: Ziad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:55:19

Próbowałem tego i działa: (proszę zastąpić to tabletką lub tabulatorem, którego używasz)

    jQuery(document).ready(function() {
        jQuery('a[data-toggle="pill"]').on('show.bs.tab', function(e) {
            localStorage.setItem('activeTab', jQuery(e.target).attr('href'));
        });

        // Here, save the index to which the tab corresponds. You can see it 
        // in the chrome dev tool.
        var activeTab = localStorage.getItem('activeTab');

        // In the console you will be shown the tab where you made the last 
        // click and the save to "activeTab". I leave the console for you to 
        // see. And when you refresh the browser, the last one where you 
        // clicked will be active.
        console.log(activeTab);

        if (activeTab) {
           jQuery('a[href="' + activeTab + '"]').tab('show');
        }
    });
Mam nadzieję, że to komuś pomoże.

Oto wynik: https://jsfiddle.net/neilbannet/ego1ncr5/5/

 4
Author: Neil Bannet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-19 18:40:44

Mój kod, działa dla mnie, używam localStorage HTML5

$('#tabHistory  a').click(function(e) {
  e.preventDefault();
  $(this).tab('show');
});
$("ul.nav-tabs#tabHistory > li > a").on("shown.bs.tab", function(e) {
  var id = $(e.target).attr("href");
  localStorage.setItem('selectedTab', id)
});
var selectedTab = localStorage.getItem('selectedTab');
$('#tabHistory a[href="' + selectedTab + '"]').tab('show');
 3
Author: Nguyen Pham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-14 22:29:06

Ponieważ nie mogę jeszcze skomentować skopiowałem odpowiedź z góry, to naprawdę mi pomogło. Ale zmieniłem go do pracy z plikami cookie zamiast # id, więc chciałem podzielić się zmianami. Umożliwia to Przechowywanie aktywnej karty dłużej niż tylko jedno odświeżanie (np. wielokrotne przekierowanie) lub gdy identyfikator jest już użyty i nie chcesz implementować metody koppors split.

<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);
    $.cookie('activeTab', id);
});

    // on load of the page: switch to the currently selected tab
    var hash = $.cookie('activeTab');
    if (hash != null) {
        $('#myTab a[href="#' + hash + '"]').tab('show');
    }
</script>
 2
Author: Joeri Landman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-11 16:26:39

Wypróbowałem kod oferowany przez Xavi Martínez . Zadziałało, ale nie dla IE7. Problem w tym , że Zakładki nie odnoszą się do żadnej odpowiedniej treści.
Więc wolę ten kod do rozwiązania tego problemu.

function pageLoad() {
  $(document).ready(function() {

    var tabCookieName = "ui-tabs-1"; //cookie name
    var location = $.cookie(tabCookieName); //take tab's href

    if (location) {
      $('#Tabs a[href="' + location + '"]').tab('show'); //activate tab
    }

    $('#Tabs a').click(function(e) {
      e.preventDefault()
      $(this).tab('show')
    })

    //when content is alredy shown - event activate 
    $('#Tabs a').on('shown.bs.tab', function(e) {
      location = e.target.hash; // take current href
      $.cookie(tabCookieName, location, {
        path: '/'
      }); //write href in cookie
    })
  });
};
 2
Author: Vitalii Isaenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:33:26

Cóż, to już w 2018 roku, ale myślę, że lepiej późno niż wcale (jak tytuł w programie telewizyjnym), lol. Na dole jest kod jQuery, który tworzę podczas pracy dyplomowej.

<script type="text/javascript">
$(document).ready(function(){
    $('a[data-toggle="tab"]').on('show.affectedDiv.tab', function(e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    });
    var activeTab = localStorage.getItem('activeTab');
    if(activeTab){
        $('#myTab a[href="' + activeTab + '"]').tab('show');
    }
});
</script>

A oto kod do zakładek bootstrap:

<div class="affectedDiv">
    <ul class="nav nav-tabs" id="myTab">
        <li class="active"><a data-toggle="tab" href="#sectionA">Section A</a></li>
        <li><a data-toggle="tab" href="#sectionB">Section B</a></li>
        <li><a data-toggle="tab" href="#sectionC">Section C</a></li>
    </ul>
    <div class="tab-content">
        <div id="sectionA" class="tab-pane fade in active">
            <h3>Section A</h3>
            <p>Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui. Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth.</p>
        </div>
        <div id="sectionB" class="tab-pane fade">
            <h3>Section B</h3>
            <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
        </div>
        <div id="sectionC" class="tab-pane fade">
            <h3>Section C</h3>
            <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
        </div>
    </div>
</div>


Dont forget to call the bootstrap and other fundamental things 

Oto szybkie kody dla Ciebie:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


Przejdźmy teraz do wyjaśnienia:

Kod jQuery w powyższym przykładzie po prostu pobiera element wartość atrybutu href, gdy nowa karta została pokazane przy użyciu jQuery .metoda attr() i zapisać ją lokalnie w przeglądarce użytkownika poprzez HTML5 obiekt localStorage. Później, gdy użytkownik odświeży stronę to pobiera te dane i aktywuje powiązaną kartę za pośrednictwem .tab ('show') metoda.

Szukasz przykładów? to dla was.. https://jsfiddle.net/Wineson123/brseabdr/

Chciałbym, żeby moja odpowiedź mogła wam pomóc.. Na razie! :)
 2
Author: Mr. Winson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-07 09:57:34

Dzięki za podzielenie się.

Przez odczytanie wszystkich rozwiązań. Wymyśliłem rozwiązanie, które używa skrótu url lub localStorage w zależności od dostępności tego ostatniego z poniższym kodem:

$(function(){
    $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    })

    var hash = window.location.hash;
    var activeTab = localStorage.getItem('activeTab');

    if(hash){
          $('#project-tabs  a[href="' + hash + '"]').tab('show');   
    }else if (activeTab){
        $('#project-tabs a[href="' + activeTab + '"]').tab('show');
    }
});
 1
Author: Vaibhav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-07 18:00:15

Używając html5 przygotowałem ten:

Niektóre gdzie na stronie:

<h2 id="heading" data-activetab="@ViewBag.activetab">Some random text</h2>

Viewbag powinien zawierać tylko id strony / elementu np.: "testowanie"

Stworzyłem stronę.js i dodał skrypt na stronie:

/// <reference path="../jquery-2.1.0.js" />
$(document).ready(
  function() {
    var setactive = $("#heading").data("activetab");
    var a = $('#' + setactive).addClass("active");
  }
)

Teraz wszystko, co musisz zrobić, to dodać swój IDENTYFIKATOR do paska nawigacyjnego. Np.:

<ul class="nav navbar-nav">
  <li **id="testing" **>
    @Html.ActionLink("Lalala", "MyAction", "MyController")
  </li>
</ul>

All hail the data atrybut:)

 0
Author: Theodor Alexander Hkansson Hei,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-14 22:28:28

Oprócz odpowiedzi Xaviego Martíneza unikanie skoku przy kliknięciu

Unikanie Skoku

$(document).ready(function(){

    // show active tab

    if(location.hash) {

        $('a[href=' + location.hash + ']').tab('show');
    }

    // set hash on click without jumb

    $(document.body).on("click", "a[data-toggle]", function(e) {

        e.preventDefault();

        if(history.pushState) {

            history.pushState(null, null, this.getAttribute("href"));
        }
        else {

            location.hash = this.getAttribute("href");
        }

        $('a[href=' + location.hash + ']').tab('show');

        return false;
    });
});

// set hash on popstate

$(window).on('popstate', function() {

    var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");

    $('a[href=' + anchor + ']').tab('show');
});

Zagnieżdżone karty

Implementacja ze znakiem " _ " jako separatorem

$(document).ready(function(){

    // show active tab

    if(location.hash) {

        var tabs = location.hash.substring(1).split('_');

        $.each(tabs,function(n){

            $('a[href=#' + tabs[n] + ']').tab('show');
        });         

        $('a[href=' + location.hash + ']').tab('show');
    }

    // set hash on click without jumb

    $(document.body).on("click", "a[data-toggle]", function(e) {

        e.preventDefault();

        if(history.pushState) {

            history.pushState(null, null, this.getAttribute("href"));
        }
        else {

            location.hash = this.getAttribute("href");
        }

        var tabs = location.hash.substring(1).split('_');

        //console.log(tabs);

        $.each(tabs,function(n){

            $('a[href=#' + tabs[n] + ']').tab('show');
        });

        $('a[href=' + location.hash + ']').tab('show');

        return false;
    });
});

// set hash on popstate

$(window).on('popstate', function() {

    var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");

    var tabs = anchor.substring(1).split('_');

    $.each(tabs,function(n){

        $('a[href=#' + tabs[n] + ']').tab('show');
    });

    $('a[href=' + anchor + ']').tab('show');
});
 0
Author: RafaSashi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-20 15:12:46

Użyliśmy jQuery trigger aby onload mieć skrypt wciśnięty przycisk dla nas

$(".class_name").trigger ('click');

 0
Author: Dan Kaiser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-30 23:01:47

Biada, jest na to tyle sposobów. Wymyśliłem to, krótko i prosto. Mam nadzieję, że to pomoże innym.

  var url = document.location.toString();
  if (url.match('#')) {
    $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
  } 

  $('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
    if(e.target.hash == "#activity"){
      $('.nano').nanoScroller();
    }
  })
 0
Author: user752746,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-17 16:33:37

Jest rozwiązanie po przeładowaniu strony i zachowaniu oczekiwanego zaznaczona karta.

Załóżmy, że po zapisaniu danych przekierowany adres url to: my_url # tab_2

Teraz poprzez następujący skrypt zakładka oczekiwana pozostanie wybrane.

$(document).ready(function(){
    var url = document.location.toString();
    if (url.match('#')) {
        $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
        $('.nav-tabs a').removeClass('active');
    }
});
 0
Author: Hasib Kamal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-22 08:01:07