Find Active Tab using jQuery and Twitter Bootstrap

后端 未结 3 627
失恋的感觉
失恋的感觉 2020-12-28 11:39

I\'ve been racking my brain for a little while now, and I would like to know if anyone out there knows how I can find the active tab, using jQuery and Twitter\'s Bootstrap.

相关标签:
3条回答
  • 2020-12-28 11:59

    First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.

      <ul class='nav nav-tabs'>
        <li class='active'><a href='#home'>Home</a></li>
        <li><a href='#menu1'>Menu 1</a></li>
        <li><a href='#menu2'>Menu 2</a></li>
        <li><a href='#menu3'>Menu 3</a></li>
      </ul>
    
      <div class='tab-content'>
        <div id='home' class='tab-pane fade in active'>
          <h3>HOME</h3>
        <div id='menu1' class='tab-pane fade'>
          <h3>Menu 1</h3>
        </div>
        <div id='menu2' class='tab-pane fade'>
          <h3>Menu 2</h3>
        </div>
        <div id='menu3' class='tab-pane fade'>
          <h3>Menu 3</h3>
        </div>
      </div>
    </div>
    
    <script>
    $(document).ready(function(){
    // Handling data-toggle manually
        $('.nav-tabs a').click(function(){
            $(this).tab('show');
        });
    // The on tab shown event
        $('.nav-tabs a').on('shown.bs.tab', function (e) {
            alert('Hello from the other siiiiiide!');
            var current_tab = e.target;
            var previous_tab = e.relatedTarget;
        });
    });
    </script>
    
    0 讨论(0)
  • 2020-12-28 12:00

    Twitter Bootstrap assigns the active class to the li element that represents the active tab:

    $("ul#sampleTabs li.active")
    

    An alternative is to bind the shown event of each tab, and save the active tab:

    var activeTab = null;
    $('a[data-toggle="tab"]').on('shown', function (e) {
      activeTab = e.target;
    })
    
    0 讨论(0)
  • 2020-12-28 12:21

    Here is the answer for those of you who need a Boostrap 3 solution.

    In bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line

    // tab
    $('#rowTab a:first').tab('show');
    
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    //show selected tab / active
     console.log ( $(e.target).attr('id') );
    });
    
    0 讨论(0)
提交回复
热议问题