Bootstrap linking to a tab with an url

前端 未结 3 524
旧时难觅i
旧时难觅i 2020-12-03 09:01

I am working with bootstrap 3, and I am having some problems on linking a url to a specific tab, the panel changes but the activated tab doesnt. So I want the line <

相关标签:
3条回答
  • 2020-12-03 09:12

    In order to activate the tab you can use jQuery plugin as shown in bootstrap. So you can add this piece of jQuery code to your program to enable the tab:

    $(function () {
        $('#tab1 a').click(function (e) {
            e.preventDefault();
            $('a[href="' + $(this).attr('href') + '"]').tab('show');
        })
    });
    

    You can check this link: Updated code

    0 讨论(0)
  • 2020-12-03 09:14

    The activating of the tab depends of the ul structure. In your example case you could overwrite the click event of the plugin by adding to the end of your document (after Boostrap's Javascript):

    $(function(){
        $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
        e.preventDefault()
        if($(this).parent().prop('tagName')!=='LI')
        {
    
            $('ul.nav li a[href="' + $(this).attr('href') + '"]').tab('show');
        }   
        else
        {
            $(this).tab('show')
        }
      })
    });
    

    Ref: Get element type with jQuery

    Note: a shorter version will also work in this case:

    $(function(){
        $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
        e.preventDefault()
        $('ul.nav li a[href="' + $(this).attr('href') + '"]').tab('show');
     })
     });
    
    0 讨论(0)
  • 2020-12-03 09:35

    Like Rohitha's answer, but a little more general:

    $(function () {
      $('a.link-to-tab').click(function (e) {
        e.preventDefault();
        $('a[href="' + $(this).attr('href') + '"]').tab('show');
      })
    });
    

    Works for any anchor tag with class="link-to-tab" and an href to the tab id to be shown. For example, <a class="link-to-tab" href="#tab2">.

    0 讨论(0)
提交回复
热议问题