jQuery removeClass 在父/兄弟/子上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3972944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery removeClass on parent/sibling/child
提问by simonyoung
I am using the following jQuery to change classes on elements in an unordered list. It doesn't seem like it is the most effective way of achieving the effect. Is there a better way to write this?
我正在使用以下 jQuery 更改无序列表中元素的类。这似乎不是实现效果的最有效方法。有没有更好的方法来写这个?
$(function() {
$('nav li a').click( function() {
$(this).parent().siblings().children().removeClass('active');
$(this).addClass('active');
});
});
Thanks
谢谢
S
秒
回答by Nick Craver
It's usually simpler in these cases to attach the handler to the <li>
and let the click bubble upfrom the <a>
(which happens by default). Then your handler looks like this:
在这些情况下,将处理程序附加到<li>
并让点击从冒泡<a>
(默认情况下发生)通常更简单。然后你的处理程序看起来像这样:
$(function() {
$('nav li').click( function() {
$(this).addClass('active').siblings().removeClass('active');
});
});
Then in your CSS you just account for active
being on the <li>
, like this:
然后在您的 CSS 中,您只需考虑active
在 上<li>
,如下所示:
li.active a { color: red; }
As an aside, if you have many <li>
elements you'll want to use .delegate()
like this:
顺便说一句,如果你有很多<li>
元素,你会想像这样使用.delegate()
:
$('nav').delegate('li', 'click', function() {
$(this).addClass('active').siblings().removeClass('active');
});
回答by jcolebrand
Also note that if you want to remove 'active'
from all elements except this
then you could get away with something as simple as
另请注意,如果您想'active'
从所有元素中删除,除此之外,this
您可以使用一些简单的方法
$('.active').removeClass('active');
$(this).addClass('active');
And that should propagate through the tree pretty easily. However, I can see it causing a headache on performance if the DOM is heavily populated.
这应该很容易在树中传播。但是,如果 DOM 被大量填充,我可以看到它会导致性能问题。
回答by vishal
I used above code, it is working
我使用了上面的代码,它正在工作
I am using in my code
我在我的代码中使用
enter code here : function addnewStepsUpper(){
jQuery('.hide_upper_clone_class').clone().insertAfter(".upper_clone_class1");
jQuery('.upper_clone_class1').siblings().removeClass('hide_upper_clone_class');
}
}
Thanks Vishal Sanwar
感谢维沙尔·桑瓦尔