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

后端 未结 2 873
粉色の甜心
粉色の甜心 2020-12-03 15:48

I know this question was asked before and answered in the following post:

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

Ho

相关标签:
2条回答
  • 2020-12-03 16:26

    I prefer to use a pushstate.

    It seems more like "The web way..." to me and it allows me to have external links pointing right to the tab I want to show.

    This is my function:

    function setBootstrapTabs()
    {
        var activeTab = "#" + getParameterByName("submenu");
    
        $('a[data-toggle="tab"]').on('shown', function () {
            //save the latest tab;
            var new_url = updateUrlParam("submenu",
                $(this).attr('href').replace("#",""));
            window.history.replaceState({
                    turbolinks: true, position: Date.now()
                }, document.title, new_url
            );
        });
    
        if (activeTab.length > 0) {
            $('a[href=' + activeTab + ']').tab('show');
        }
    };
    
    0 讨论(0)
  • 2020-12-03 16:42

    As Tommi Komulainen wrote: e.target contains the full url including the hash. You only need the hash. So use e.target.toString().split('#')[1]); or even better $(this).attr('href') $('#'+lastTab).tab('show'); applies the .tab() on the div with id = #{lastTab} while you need to apply on the link (a tag) with data-toggle. So use: $('a[href=#' + lastTab + ']').tab('show'); here.

    The complete function to use:

                      $(function() 
                        { 
                          $('a[data-toggle="tab"]').on('shown', 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 (lastTab) {
                             $('a[href=' + lastTab + ']').tab('show');
                          }
                          else
                          {
                            // Set the first tab if cookie do not exist
                            $('a[data-toggle="tab"]:first').tab('show');
                          }
                      });
    

    update: see https://stackoverflow.com/a/16016592/1596547 so remove the active class from your source and set the first tab active when lastTab is not set.

    0 讨论(0)
提交回复
热议问题