2

I'm using bootstrap tabs in one of my application and I have a challenge where shown.bs.tab event is not getting triggered when page is loaded with default active tab.

In the below code I have a tab named "Home" which is an default tab (active class added). On page load, my "Home" tab content is shown perfectly, but the challenge is the 'shown.bs.tab' event attached to that tab is not triggered. The same event is triggered when I navigate to "Menu 1" tab and then come back to "Home" tab.

<ul class="nav nav-tabs">
   <li class="active"><a data-toggle="tab" href="#home">Home</a></li>
   <li><a data-toggle="tab" href="#menu1">Menu 1</a></li>
</ul>

<div class="tab-content">
  <div id="home" class="tab-pane fade in active">
    <h3>HOME</h3>
    <p>Some content.</p>
  </div>
  <div id="menu1" class="tab-pane fade">
    <h3>Menu 1</h3>
    <p>Some content in menu 1.</p>
  </div>
</div>

<script>
  $(document).ready(function(){
     $("a[href='#home']").on('shown.bs.tab', function (e) {
       alert('tab shown');
     });
  });
</script>

How do I make this event trigger on page load? The intention behind this is content of "Home" tab is dynamic which is response of Ajax call which gets triggered on tab is shown.

4

2 回答 2

3

通过从 HTML 中删除“活动”类并添加脚本以选择默认显示的选项卡来解决此问题。

以下是更新后的脚本。

<script>
    $(document).ready(function(){
       $("a[href='#home']").on('shown.bs.tab', function (e) {
          alert('tab shown');
       }).tab('show');
    });
</script>

使用此脚本,当显示“主页”选项卡时,将触发事件。此外,从其他选项卡返回时也会触发相同的操作。

于 2016-08-23T12:56:51.840 回答
0

就我而言,active从选项卡中删除类并.tab('show')在绑定事件后添加部分解决了问题,但不是打开第一个选项卡,而是打开了最后一个选项卡。我的解决方案是删除active该类并将这一行添加到 javascript:

$('a[data-toggle="tab"]').first().tab('show');
于 2019-10-24T16:16:26.793 回答