【问题标题】:Bootstrap tabs shown.bs.tab not fired on page loadBootstrap tabs shown.bs.tab 在页面加载时未触发
【发布时间】:2017-07-05 15:01:27
【问题描述】:

我在页面上有几个标签,我试图在页面重新加载时保持标签处于活动状态。我通过将哈希推入 url 来做到这一点:

$('.nav-tabs a[data-toggle="tab"]').click(function () {
    window.history.pushState("", "", $(this).attr('href'));
});

使用上面的代码,即使用户重新加载页面,我也会保持选项卡处于活动状态。

我正在尝试捕捉 shown.bs.tab 事件,但显然事件不会在页面重新加载时触发,但在单击任何其他选项卡时它会起作用

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

知道我做错了什么吗?

编辑

active 类已从 lidiv.tab-pane 中删除

我什至尝试手动调用 tab.show 事件,但没有帮助

var hash = window.location.hash;
if(hash) {
    $('.nav-tabs a[href="' + hash + '"]').tab('show'); //or trigger('click')
}

【问题讨论】:

  • 页面加载时触发“点击”的原因是什么?我认为您需要致电 .tab('show') 来触发 shown.bs.tab 事件。
  • 不,调用.tab('show').trigger('click') 也不起作用。我已经更新了我的问题

标签: jquery twitter-bootstrap tabs


【解决方案1】:

确保在调用.tab('show')之前附加shown.bs.tab处理程序:

// wire up shown event
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    console.log("tab shown...");
});

// read hash from page load and change tab
var hash = document.location.hash;
var prefix = "tab_";
if (hash) {
    $('.nav-tabs a[href="'+hash.replace(prefix,"")+'"]').tab('show');
} 

Bootstrap 4 - 重新加载时选择活动标签

代码:http://www.codeply.com/go/Yu8wbjeGMZ
演示:http://www.codeply.com/render/Yu8wbjeGMZ#tab2

【讨论】:

    【解决方案2】:

    似乎.tab('show'); 不会在已显示的选项卡上触发事件。

    相反,我已将其替换为 .trigger('shown.bs.tab'); 并且它可以正常工作,所以我的代码现在看起来像这样:

    var hash = window.location.hash;
    if (hash) {
        $('.nav-tabs a[href="' + hash + '"]').trigger('show.bs.tab');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      相关资源
      最近更新 更多