引导3 jQuery的事件活动选项卡更改

我花了不切实际的时间试图启动引导3选项卡/导航栏的选项卡更改时触发一个函数和字面上所有build议谷歌吐出错误/没有工作。

如何去做这个?

元编辑:看评论

Eric Saupe知道如何去做: http ://ericsaupe.com/tag/bootstrap-3-tabs-example-ajax/

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { var target = $(e.target).attr("href") // activated tab alert(target); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <ul id="myTab" class="nav nav-tabs"> <li class="active"><a href="#home" data-toggle="tab">Home</a></li> <li class=""><a href="#profile" data-toggle="tab">Profile</a></li> </ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane fade active in" id="home"> home tab! </div> <div class="tab-pane fade" id="profile"> profile tab! </div> </div> 
 $(function () { $('#myTab a:last').tab('show'); }); $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { var target = $(e.target).attr("href"); if ((target == '#messages')) { alert('ok'); } else { alert('not ok'); } }); 

问题是attr('href')永远不会是空的。

或者比较#id =“#some值”,然后调用ajax。

感谢@ Gerben的post,知道有两个事件show.bs.tab(在显示标签之前)和shown.bs.tab(在显示标签之后),如文档中所述 – 引导标签的使用

如果我们只对特定的选项卡感兴趣,并且可能添加单独的函数,而不必在一个函数中添加if-else块,那么额外的解决scheme就是使用hrefselect器(如果需要,还可以使用额外的select器)

  $("a[href='#tab_target_id']").on('shown.bs.tab', function(e) { console.log('shown - after the tab has been shown'); }); // or even this one if we want the earlier event $("a[href='#tab_target_id']").on('show.bs.tab', function(e) { console.log('show - before the new tab has been shown'); }); 

演示

要添加到Mosh Feu答案,如果在我的情况下在飞行中创build的选项卡,您将使用下面的代码

 $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) { var tab = $(e.target); var contentId = tab.attr("href"); //This check if the tab is active if (tab.parent().hasClass('active')) { console.log('the tab with the content id ' + contentId + ' is visible'); } else { console.log('the tab with the content id ' + contentId + ' is NOT visible'); } }); 

我希望这可以帮助别人

这对我有效。

 $('.nav-pills > li > a').click( function() { $('.nav-pills > li.active').removeClass('active'); $(this).parent().addClass('active'); } );