Twitter Bootstrap - Tabs - URL doesn't change

前端 未结 15 1540
长情又很酷
长情又很酷 2020-11-28 18:53

I\'m using Twitter Bootstrap and its \"tabs\".

I have the following code:

相关标签:
15条回答
  • 2020-11-28 19:23

    There is also a simple way to react on hash changes (e.g. back button). Simply add an hashchange event listener to tomaszbak solution:

    $(function(){
      // Change tab on load
      var hash = window.location.hash;
      hash && $('ul.nav a[href="' + hash + '"]').tab('show');
    
      $('.nav-tabs a').click(function (e) {
        $(this).tab('show');
        var scrollmem = $('body').scrollTop();
        window.location.hash = this.hash;
        $('html,body').scrollTop(scrollmem);
      });
    
      // Change tab on hashchange
      window.addEventListener('hashchange', function() {
        var changedHash = window.location.hash;
        changedHash && $('ul.nav a[href="' + changedHash + '"]').tab('show');
      }, false);
    });
    
    0 讨论(0)
  • 2020-11-28 19:24

    As your anchor elements already change the url hash, listening to onhashchange event is another good option. As @flori already mentioned, this method works nice with the browser back button.

    var tabs$ = $(".nav-tabs a");
    
    $( window ).on("hashchange", function() {
        var hash = window.location.hash, // get current hash
            menu_item$ = tabs$.filter('[href="' + hash + '"]'); // get the menu element
    
        menu_item$.tab("show"); // call bootstrap to show the tab
    }).trigger("hashchange");
    

    Finally, triggering the event just after you define the listener will also help showing the right tab on page load.

    0 讨论(0)
  • 2020-11-28 19:29

    Most simple, assuming you're using the documented data-toggle="tab" syntax described here:

    $(document).on('shown.bs.tab', function(event) {
      window.location.hash = $(event.target).attr('href');
    });
    
    0 讨论(0)
提交回复
热议问题