Linking to a Bootstrap Tab from outside - how to set the tab to “active”?

前端 未结 7 1182
清歌不尽
清歌不尽 2020-12-01 17:10

I have a Bootstrap \"tab\" navigation with 3 different content tabs. It works perfectly except that I want to link to one of the tabs from OUTSIDE the tab navigation. Meanin

7条回答
  •  情书的邮戳
    2020-12-01 17:46

    Below the little trick I did that works for me.

    I can call the webpage adding the bootstrap pill id to the URL.

    For instance calling mypage.html#other_id will display the pill matching #other_id

    
    
    ...
    ...

    Here the JQuery code:

    $(document).ready(function(){
        //Manage hash in URL to open the right pill
        var hash = window.location.hash;
        // If a hash is provided 
        if(hash && hash.length>0)
        {
            // Manage Pill titles
            $('ul.nav-pills li a').each(function( index ) {
                if($(this).attr('href')==hash)
                    $(this).parent('li').addClass('active');
                else
                    $(this).parent('li').removeClass('active');
            });
            // Manage Tab content
            var hash = hash.substring(1); // Remove the #
            $('div.tab-content div').each(function( index ) {
                if($(this).attr('id')==hash)
                    $(this).addClass('active');
                else
                    $(this).removeClass('active');
            });
        }
    });
    

    Edit: My code is not exactly what you need but you can update it to match your needs. Tell me if you need explanations

提交回复
热议问题