Bootstrap3标签执行" shown.bs.tab"在装载

时间:2017-02-01 19:15:28

标签: jquery twitter-bootstrap-3

在Bootstrap中,仅当有人单击选项卡时,才会执行以下事件。那么,如何在加载默认活动页面时使其执行,并且活动选项卡是动态的。

 $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
       // Do something
 });

LinK bootstrap3 tabs 感谢

3 个答案:

答案 0 :(得分:0)

您可以尝试在加载后单击活动选项卡,然后触发shown.bs.tab函数

$(".nav-tabs li.active a").click();

或者只是使用活动标签的信息来执行你想要的代码

function doSomething(target) {
    // do something with the target here
    // not sure what you want to do?
}

$(document).ready(function() {
    // this happens on clicking a tab
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        doSomething(e.target);
    });

    // this happens on page load
    doSomething($(".nav-tabs li.active a"));
});

答案 1 :(得分:0)

我不确定你在问什么,但有几种方法可以触发shown.bs.tab事件。您可以单击选项卡,触发单击带有jQuery(.trigger('click'))的选项卡或使用.tab('show')

如果您在shown.bs.tab事件发生后询问如何确定活动标签窗格,可以这样做..

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var target = $(e.target).attr("href"); // activated tab pane
});

演示:http://www.codeply.com/go/UaQqzIFDfK

答案 2 :(得分:0)

HTML(必须在加载时打开的标签):

<li role="presentation" class="active-on-load"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>

JS:

// Event delegation

$('.nav-tabs').on('shown.bs.tab', '[data-toggle="tab"]', function() {
  console.log('Shown');
});

// Show active tab on load (remove active class from li and add your custom class)

$('.nav-tabs > .active-on-load > a').tab('show');

// If you have dynamic tabs - this is just a test to check if shown event is fired on dynamic added tabs (yes - thanks to event delegation)

var id = 0;
$('#addnew').click(function(e) {
  e.preventDefault();
  $('.nav-tabs').append('<li role="presentation"><a href="#newtab' + id + '" aria-controls="newtab" role="tab" data-toggle="tab">New tab' + id + '</a></li>');
  $('.tab-content').append('<div role="tabpanel" class="tab-pane" id="newtab' + id + '">New tab ' + id + '</div>');
  id += 1;
});

CODEPEN