Ger*_*art 274 jquery twitter-bootstrap-3
当引导程序3选项卡/导航栏的选项卡更改时,我花费了不切实际的时间尝试触发功能,并且字面上所有建议谷歌吐出错误/不起作用.
怎么去这个?
元编辑:见评论
Ger*_*art 424
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target = $(e.target).attr("href") // activated tab
alert(target);
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
Flo*_*rin 85
$(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');
}
});
Run Code Online (Sandbox Code Playgroud)
问题是attr('href')永远不会是空的.
或者比较#id ="#some value"然后调用ajax.
msa*_*jay 32
感谢@ Gerben的帖子后来了解有两个事件show.bs.tab(显示选项卡之前)和shown.bs.tab(显示选项卡之后),如文档中所述 - Bootstrap Tab用法
如果我们只对特定选项卡感兴趣,并且可能添加单独的函数而不必在一个函数中添加if - else块,那么另一个解决方案是使用a href选择器(如果需要,可以使用其他选择器)
$("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');
});
Run Code Online (Sandbox Code Playgroud)
Jay*_*len 10
要添加到Mosh Feu的答案,如果像我一样在运行中创建的选项卡,您将使用以下代码
$(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');
}
});
Run Code Online (Sandbox Code Playgroud)
我希望这可以帮助别人
小智 8
这对我有用.
$('.nav-pills > li > a').click( function() {
$('.nav-pills > li.active').removeClass('active');
$(this).parent().addClass('active');
} );
Run Code Online (Sandbox Code Playgroud)