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

后端 未结 2 875
粉色の甜心
粉色の甜心 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: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.

提交回复
热议问题