我有两个级别列表
<ul>
<li></li>
<li></li>
<li>
<ol>
<li></li>
<li class="active"></li>
<li></li>
</ol>
</li>
<li></li>
<li></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
我如何使用内部LI活动类将新类添加到父LI中,如
<ul>
<li class="parent">
<ol>
<li class="active">
Run Code Online (Sandbox Code Playgroud)
你应该使用:
$('.active').parents('li:first').addClass('parent');
Run Code Online (Sandbox Code Playgroud)
如果你想得到第一个父母或:
$('.active').parents('li').addClass('parent');
Run Code Online (Sandbox Code Playgroud)
如果你想得到所有的父母.
jQuery有这个closest()方法.通常,这是我们应该使用的,但在这种情况下,.closest('li')将返回自己,因为它包含检查中的当前元素.
但是,正如A.Wolff指出的那样,你可以:not()在选择器中使用它来排除活动的那个,就像那样:
$('.active').closest('li:not(.active)').addClass('parent');
Run Code Online (Sandbox Code Playgroud)