如何使用 javascript 切换 Bootstrap 5 选项卡(按钮版本)
2021-08-06
3054
我想要可编程切换选项卡(使用 bootstrap 5)。Bootsrap 文档说:
As a best practice, we recommend using elements for the tabs, as these are controls that trigger a dynamic change, rather than links that navigate to a new page or location.
所以我想使用按钮而不是链接。代码:
$("#mybut").click(function() {
var sel = document.querySelector('#nav-tab-manager')
bootstrap.Tab.getInstance(sel).show()
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
<div class="nav nav-tabs" id="nav-tab" role="tablist">
<button class="nav-link active" id="nav-tabs-order" data-bs-toggle="tab" data-bs-target="#tabs-1" type="button" role="tab" aria-controls="tabs-1" aria-selected="true">Orders
</button>
<button class="nav-link" id="nav-tab-manager" data-bs-toggle="tab" data-bs-target="#tabs-2" type="button" role="tab" aria-controls="tabs-2" aria-selected="false">Managers
</button>
</div>
</nav>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="tabs-1" role="tabpanel" aria-labelledby="tabs-tab1">
Orders
</div>
<div class="tab-pane fade" id="tabs-2" role="tabpanel" aria-labelledby="tabs-2">
Managers
</div>
</div>
<button type="button" class="btn btn-primary" id="mybut">Want switch to manager</button>
问题是选择器错误。但我不知道为什么。
1个回答
您将需要使用
getOrCreateInstance
,因为 Tabs 不会首先通过 JS 初始化。
$("#mybut").click(function() {
var sel = document.querySelector('#nav-tab-manager')
bootstrap.Tab.getOrCreateInstance(sel).show()
})
Carol Skelly
2021-08-06