Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

前端 未结 24 1984
夕颜
夕颜 2020-11-22 04:57

I\'m developing a web page in which I\'m using Twitter\'s Bootstrap Framework and their Bootstrap Tabs JS. It works great except for a few minor issues, one of which is I do

24条回答
  •  天命终不由人
    2020-11-22 05:18

    I am not a big fan of if...else; so I took a simpler approach.

    $(document).ready(function(event) {
        $('ul.nav.nav-tabs a:first').tab('show'); // Select first tab
        $('ul.nav.nav-tabs a[href="'+ window.location.hash+ '"]').tab('show'); // Select tab by name if provided in location hash
        $('ul.nav.nav-tabs a[data-toggle="tab"]').on('shown', function (event) {    // Update the location hash to current tab
            window.location.hash= event.target.hash;
        })
    });
    
    1. Pick a default tab (usually the first)
    2. Switch to tab (if such an element is indeed present; let jQuery handle it); Nothing happens if a wrong hash is specified
    3. [Optional] Update the hash if another tab is manually chosen

    Doesn't address scrolling to requested hash; but should it?

提交回复
热议问题