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

前端 未结 24 1809
夕颜
夕颜 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:02

    This is my solution to handle nested tabs. I just added a function to check if the active tab has a parent tab to be activated. This is the function:

    function activateParentTab(tab) {
        $('.tab-pane').each(function() {
            var cur_tab = $(this);
            if ( $(this).find('#' + tab).length > 0 ) {
                $('.nav-tabs a[href=#'+ cur_tab.attr('id') +']').tab('show');
                return false;
            }
        });
    }
    

    And can be called like this (Based on @flynfish's solution):

    var hash = document.location.hash;
    var prefix = "";
    if (hash) {
        $('.nav-tabs a[href='+hash.replace(prefix,"")+']').tab('show');
        activateParentTab(hash);
    } 
    
    // Change hash for page-reload
    $('.nav-tabs a').on('shown', function (e) {
        window.location.hash = e.target.hash.replace("#", "#" + prefix);
    });
    

    This solution works pretty fine to me at the moment. Hope this can be useful for someone else ;)

提交回复
热议问题