Bootstrap nav-tabs使用jquery检查选定的选项卡

时间:2015-11-16 22:15:21

标签: javascript jquery twitter-bootstrap

我有以下Bootstrap导航标签:

 <div class="row spiff_tabs_body">
            <!-- Nav tabs -->
            <ul class="nav nav-tabs spiff_tabs" role="tablist">
                <li role="presentation" class="active">
                    <a href="#home" aria-controls="home" role="tab" data-toggle="tab" onclick="FormGet('dashboard/delayedspiff', 'delayedspiff')">Potential Spiff</a>
                </li>
                <li role="presentation">
                    <a href="#profile" aria-controls="profile" role="tab" data-toggle="tab" onclick="FormGet('dashboard/instantspiff', 'delayedspiff')">Instant Spiff</a>
                </li>
            </ul>
            <!-- Tab panes -->
            <div class="tab-content">
                <div role="tabpanel" class="tab-pane active" id="delayedspiff"></div>
                <div role="tabpanel" class="tab-pane" id="instantspiff"></div>
            </div>
        </div>
    </div>
</div>

我需要能够检查选择了哪个选项卡,然后显示警告。我在视图中有以下javascript:

<script>
$(function () {
    FormGet('dashboard/delayedspiff', 'delayedspiff');        
});
</script>

<script>
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    // here is the new selected tab id
    var selectedTabId = e.target.id;
    var id = $('.tab-content .active').attr('id');
    if (id == "delayedspiff") {
        alert("delayedspiff");
    } else {
        alert("instantspiff");
    }
});   
</script>

单击选项卡时,它会起作用,但警报始终显示delayedspiff。当他们点击instantspiff选项卡时,我需要显示instantspiff。谁能看到我做错了什么?

1 个答案:

答案 0 :(得分:1)

您只需要从所有标签中删除课程active,然后将其添加到已点击的标签中。

编辑:要获取点击标签的ID,请尝试在标签选项上使用属性data-id。

  <li role="presentation" class="active">
                    <a href="#home" aria-controls="home" role="tab" data-id="delayedspiff" data-toggle="tab" onclick="FormGet('dashboard/delayedspiff', 'delayedspiff')">Potential Spiff</a>
                </li>
                <li role="presentation">
                    <a href="#profile" aria-controls="profile" data-id="instantspiff" role="tab" data-toggle="tab" onclick="FormGet('dashboard/instantspiff', 'delayedspiff')">Instant Spiff</a>
                </li>

<script>
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var wrongid = $('.tab-content .active').attr('id');
    $('a[data-toggle="tab"]').removeClass("active"); // remove class active from all tabs
    $(this).addClass("active"); // add class active to the current tab
    var correctid = $(this).data("id"); // get the attribute data-id of the clicked tab
    alert($('.tab-content .active')[0].outerHTML); // shows why you are getting the incorrect id
    if (correctid == "delayedspiff") 
      alert("delayedspiff");
    else 
      alert("instantspiff");    
});   
</script>

更新了小提琴:https://jsfiddle.net/DTcHh/14313/