You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改jQuery函数实现同时控制两个ID的Bootstrap5标签页切换

多Bootstrap 5 Tablist独立箭头切换修改方案

一、HTML调整

原有代码用ID绑定箭头和tablist,多个tablist会出现ID重复冲突,需做如下修改:

  • 把原有箭头的id="previous"、id="next"改为通用类名,避免ID重复,修改后箭头代码示例:
<div class="col-6 tab-container-arrows text-end pe-4">
    <a class="prev-tab d-inline-block me-2">
        <img src="/assets/images/icons/left-arrow.svg" alt="左箭头" class="left-arrow">
    </a>
    <a class="next-tab d-inline-block ms-2">
        <img src="/assets/images/icons/right-arrow.svg" alt="右箭头" class="left-arrow">
    </a>
</div>
  • 新增的第二个tablist直接复用tab-container的包裹结构即可,内部tablist可以自定义新ID,不需要额外调整逻辑,只需保证每个tab的a标签data-index从1开始连续编号。

二、JS代码替换

将原有硬绑定固定ID的逻辑替换为通用逻辑,点击箭头时自动查找所属tab容器内对应的tablist,互不干扰:

$(document).ready(function() {
    // 下一页箭头点击逻辑
    $('.next-tab').on('click', function() {
        // 定位当前箭头所属的tab容器
        const tabContainer = $(this).closest('.tab-container');
        // 找到容器内对应的tablist
        const tabList = tabContainer.find('.nav.nav-tabs');
        const activeTab = tabList.find('li > a.active');
        const currentIndex = parseInt(activeTab.attr('data-index'));
        const totalTabs = tabList.find('li').length;
        const nextIndex = Math.min(currentIndex + 1, totalTabs);
        if (nextIndex !== currentIndex) {
            tabList.find(`li a[data-index="${nextIndex}"]`)[0].click();
        }
    });

    // 上一页箭头点击逻辑
    $('.prev-tab').on('click', function() {
        const tabContainer = $(this).closest('.tab-container');
        const tabList = tabContainer.find('.nav.nav-tabs');
        const activeTab = tabList.find('li > a.active');
        const currentIndex = parseInt(activeTab.attr('data-index'));
        const prevIndex = Math.max(currentIndex - 1, 1);
        if (prevIndex !== currentIndex) {
            tabList.find(`li a[data-index="${prevIndex}"]`)[0].click();
        }
    });
});

修改完成后可支持任意数量的tablist,每个tablist的箭头只会控制自身容器内的标签切换。

内容的提问来源于stack exchange,提问作者user17144244

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:06:03