jquery 刷新时保持引导5选项卡状态

r1zhe5dt  于 2023-11-17  发布在  jQuery
关注(0)|答案(1)|浏览(176)
<ul class="nav nav-pills" id="my_tabs">
   <li class="nav-item" role="presentation"> 
     <a class="nav-link active" data-bs-toggle="pill" href="#tab1" aria-selected="true">Tab 1</a> 
   </li>
   <li class="nav-item" role="presentation"> 
     <a class="nav-link" data-bs-toggle="pill" href="#tab2" aria-selected="false">Tab 2</a> 
   </li>
</ul>
      
<section class="tab-content" id="tab-content">
   <div class="tab-pane active" id="tab1" role="tabpanel">
     Tab 1
   </div>
   <div class="tab-pane" id="tab2" role="tabpanel">
     Tab 2
   </div>
</section>

字符串
刷新页面后如何保持活动标签?我已经搜索过了,没有找到解决方案。提前感谢。

afdcj2ne

afdcj2ne1#

您需要使用JavaScript,而不是数据属性.
因此,使用JavaScript初始化选项卡,然后在每次单击时,将活动选项卡ID存储在localStorage中。
在第一次加载时,从localStorage获取活动选项卡ID,并将其激活,或者设置默认活动选项卡ID。
例如
(note:localStorage在SO上不工作,但它应该在本地工作,即允许保存到localStorage的地方):

const triggerTabList = document.querySelectorAll('#my_tabs a');

triggerTabList.forEach(triggerEl => {

  const tabTrigger = new bootstrap.Tab(triggerEl);

  triggerEl.addEventListener('click', event => {

    event.preventDefault();
    tabTrigger.show();

    // save tab target
    localStorage.setItem('active-tab', event.target.getAttribute('href'));

  });
});

// get the active tab id, set default
const activeTabId = localStorage.getItem('active-tab') || '#tab1';

// find the element that triggers the tab
const activeTab = [...triggerTabList].find(el => el.getAttribute('href') === activeTabId);

// click the element to trigger the tab
// in case it's not found, click the first tab
if (activeTab) {
  activeTab.click();
} else {
  triggerTabList[0].click();
}

个字符

相关问题