如果我的代码看起来像下面那样,并且喜欢将show
类添加到父级和祖级中。
// The last `nav-item` have `active` classs
<div class="nested-group nested-item show">
<div class="nested-item show">
<div class="nested-item show">
<div class="nested-item show">
<a class="nav-item active" href="#">Lorem</a>
<a class="nav-item" href="#">Ipsum</a>
</div>
</div>
</div>
</div>
// The last `nav-item` doesn't have `active` class
<div class="nested-group nested-item">
<div class="nested-item">
<div class="nested-item">
<div class="nested-item">
<a class="nav-item" href="#">Lorem</a>
<a class="nav-item" href="#">Ipsum</a>
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
您可以使用.parents()
方法定位nested-item
类的所有父/祖先。
$('.active.nav-item').parents('.nested-item').addClass('show');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nested-group nested-item ">
<div class="nested-item ">
<div class="nested-item ">
<div class="nested-item ">
<a class="nav-item active" href="#">Lorem</a>
<a class="nav-item" href="#">Ipsum</a>
</div>
</div>
</div>
</div>
&#13;