Bootstrap 4.6 折叠不切换(打开或关闭)
Posted
技术标签:
【中文标题】Bootstrap 4.6 折叠不切换(打开或关闭)【英文标题】:Bootstrap 4.6 Collapse Not Toggling (Opening or Closing) 【发布时间】:2021-10-24 01:28:34 【问题描述】:见以下代码sn-p。单击按钮时,我的 Bootstrap 4.6 折叠内容未打开。
奇怪的是,当我在 javascript 控制台中运行 $("#30-50hp").collapse('show')
时,它确实打开了,那么为什么按钮不做同样的事情呢?
这是我关注的相关文档: https://getbootstrap.com/docs/4.6/components/collapse/
// The following makes it work!
// $("#30-50hp").collapse('show')
<!doctype html>
<html lang="en">
<head>
<!-- Bootstrap v4.6 CSS-->
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l"
crossorigin="anonymous">
</head>
<body>
<h4>Select Your Horsepower</h4>
<p>
<button
class="btn btn-secondary"
type="button"
data-toggle="collapse"
data-target="#30-50hp"
aria-expanded="false"
aria-controls="30-50hp">
30-50 HP
</button>
</p>
<div class="collapse" id="30-50hp">
<div class="card card-body">
<h4 class="card-title">30-50 HP Card Title</h4>
<ul>
<li>List item 1</li>
</ul>
</div>
</div>
<!-- JQuery 3.5.1 per Bootstrap 4.6 docs -->
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<!-- Bootstrap v4.6 JavaScript -->
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
crossorigin="anonymous"></script>
</body>
</html>
【问题讨论】:
【参考方案1】:不要以数字开头的 ID:
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l"
crossorigin="anonymous">
<h4>Select Your Horsepower</h4>
<p>
<button
class="btn btn-secondary"
type="button"
data-toggle="collapse"
data-target="#x30-50hp"
aria-expanded="false"
aria-controls="30-50hp">
30-50 HP
</button>
</p>
<div class="collapse" id="x30-50hp">
<div class="card card-body">
<h4 class="card-title">30-50 HP Card Title</h4>
<ul>
<li>List item 1</li>
</ul>
</div>
</div>
<!-- JQuery 3.5.1 per Bootstrap 4.6 docs -->
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<!-- Bootstrap v4.6 JavaScript -->
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
crossorigin="anonymous"></script>
【讨论】:
以上是关于Bootstrap 4.6 折叠不切换(打开或关闭)的主要内容,如果未能解决你的问题,请参考以下文章
在 Bootstrap 3 中单击导航栏元素外部时如何关闭打开的折叠导航栏?
当用户在菜单外单击时,如何关闭 Bootstrap 导航栏下拉菜单?