jQuery .removeClass()如果不是.next() [英] jquery .removeClass() if NOT .next()
问题描述
我将如何从除下一个元素之外的所有元素中删除该类?
How would I go about remove the class from all elements except the next one?
例如:
<ul>
<li class="current"><a href="#">Trigger</a></li>
<li class="next"><a href="#">Trigger</a></li>
<li class="next"><a href="#">Trigger</a></li>
<li class="next"><a href="#">Trigger</a></li>
</ul>
点击触发器链接a
会从li
元素中删除所有"next"
类,但直接位于其下方的
Clicking on Trigger link a
removes all the "next"
classes from the li
elements except the one directly below
我不担心要实现这一目标的整套代码.除了除去下一个li上的类之外,我已经写了所有我需要的东西!
I'm not worried about the whole set of code to achieve this. I've written everything that I need apart from this one thing of removing the class except on the next li?!
更新:已解决
UPDATE: SOLVED
似乎我忽略了一个可行的简单解决方案:
Seems I overlooked a simple solution which works well:
$(this).parent().siblings().not().next().removeClass('next');
推荐答案
使用 .nextAll
方法,以获取当前元素之后的所有连续同级.然后,使用 .slice(1)
缩小集合.
Use the .nextAll
method to get all consecutive siblings after the current element. Then, reduce the set using .slice(1)
.
$('li a').click(function() {
$(this).parent().nextAll().slice(1).removeClass('next');
});
以前的方法仅从以后的项目中删除next
.如果您想影响所有兄弟姐妹,可以使用以下选项:
The previous method only removes next
from later items. If you want to affect all siblings, the following can be used:
$('li a').click(function() {
var $parent = $(this).parent();
$parent.siblings().not($parent.next()).removeClass('next');
});
另一个选择:从所有元素中删除next
类,然后将其添加到下一个元素.
Another option: Remove the next
class from all elements, then add it to the next element.
这篇关于jQuery .removeClass()如果不是.next()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!