bootstrap Tab 选项卡切换,刷新页面后保持当前选中状态

bootstrap 选项卡 tab 切换功能是通过 #field 完成切换的,当选择另外一个选项卡并刷新页面后,如何让页面直接显示当前已选中的状态?这里介绍一种实现方法。

  1. 首先,当点击 tab 选项卡时,用 js 将当前的 #field 标识追加到地址栏

    $('.nav-tabs a').on('shown.bs.tab', function (e) {
      history.pushState(null,null, e.target.hash);
      // location.hash = this.getAttribute("href");
    });
    
  2. 然后,当刷新页面时,获取地址栏 #field 标识,渲染 tab 选中状态

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

    至此,功能完成。

原文地址:https://www.cnblogs.com/songlen/p/13458172.html