当我从列表2(
当前,如果我打开一个列表,它将保持打开状态,并且不会关闭其他已经打开的列表。
HTML:
<ul class="components">
<!-- LIST 1 -->
<li>
<a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
Home
</a>
<ul class="collapse list-unstyled" id="list1">
<li>
<a href="#">Inicio 1</a>
</li>
<li>
<a href="#">Inicio 2</a>
</li>
<li>
<a href="#">Inicio 3</a>
</li>
</ul>
</li>
<!-- LIST 2 -->
<li>
<a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
Second home
</a>
<ul class="collapse list-unstyled" id="list2">
<li>
<a href="#">Inicio 1</a>
</li>
<li>
<a href="#">Inicio 2</a>
</li>
<li>
<a href="#">Inicio 3</a>
</li>
</ul>
</li>
<!-- LIST 3 -->
< li >
<a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
Another Home
</a>
<ul class="collapse list-unstyled" id="list3">
<li>
<a href="#">Inicio 1</a>
</li>
<li>
<a href="#">Inicio 2</a>
</li>
<li>
<a href="#">Inicio 3</a>
</li>
</ul>
</li>
</ul>
JavaScript:
$(function() {
$('.components li a').click(function(e) {
e.preventDefault();
var $this = $(this);
$this.closest('ul').children('li').removeClass('active');
$this.parent().addClass('active');
});
});
结果是所有选定的
答案 0 :(得分:1)
$(function() {
$('.components li a').click(function(e) {
e.preventDefault();
var $this = $(this);
var mainList = $this.closest('ul');
var subLists = mainList.children('li').children('ul');
mainList.children('li').removeClass('active');
subLists.addClass('collapse');
$this.parent().addClass('active');
var selectedSublist = $this.closest('li').children('ul')
if (selectedSublist.hasClass('collapse'))
selectedSublist.removeClass('collapse');
else
selectedSublist.addClass('collapse');
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="components">
<!-- LIST 1 -->
<li>
<a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
Home
</a>
<ul class="collapse list-unstyled" id="list1">
<li>
<a href="#">Inicio 1</a>
</li>
<li>
<a href="#">Inicio 2</a>
</li>
<li>
<a href="#">Inicio 3</a>
</li>
</ul>
</li>
<!-- LIST 2 -->
<li>
<a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
Second home
</a>
<ul class="collapse list-unstyled" id="list2">
<li>
<a href="#">Inicio 1</a>
</li>
<li>
<a href="#">Inicio 2</a>
</li>
<li>
<a href="#">Inicio 3</a>
</li>
</ul>
</li>
<!-- LIST 3 -->
<li>
<a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
Another Home
</a>
<ul class="collapse list-unstyled" id="list3">
<li>
<a href="#">Inicio 1</a>
</li>
<li>
<a href="#">Inicio 2</a>
</li>
<li>
<a href="#">Inicio 3</a>
</li>
</ul>
</li>
</ul>