[英]jquery/javascript: How do I remove the 'active' class from all the children of a parent element?
I have a few lists, something like so: 我有一些清单,像这样:
<div id="menu" class="divclass">
<ul id="firstlist">
<li><a href='#'>...</a></li>
<li><a href='#'>...</a></li>
<li><a href='#'>...</a></li>
</ul>
<ul id="secondlist">
<li><a href='#'>...</a></li>
<li><a href='#'>...</a></li>
<li><a href='#'>...</a></li>
</ul>
<!-- etc. - similar unordered lists follow. -->
</div>
When one of the <a>
elements is clicked, I want to clear all the <li>
elements of its list of the 'active'
class. 单击<a>
元素之一时,我想清除其'active'
类列表中的所有<li>
元素。 I've been fiddling around with .parent()
, .children()
, and .removeClass('active')
but I think I'm totally missing something because I can't get it to work. 我一直在摆弄.parent()
.children()
和.removeClass('active')
但我认为我完全错过了一些东西,因为我无法使用它。 Can anyone give me a hand? 有人可以帮我吗? This is the beginning of the script: 这是脚本的开头:
$(document).ready(function() {
$(".divclass ul li a").click(function() { ... }}
where .divclass
is the class of the div that contains the unordered lists. 其中.divclass
是包含无序列表的div的类。
Remove all 移除所有
$(".divclass ul li a").click(function() {
$(this).closest('.divclass').find('li').removeClass('active');
}};
Remove only form the same list 仅删除同一列表
$(".divclass ul li a").click(function() {
$(this).closest('ul').find('li').removeClass('active');
}};
If you also want to add the class active to the li parent of the a clicked: 如果您还想将活动类添加到单击的li父级中:
$(".divclass ul li a").click(function() {
$(this).parent().addClass('active').siblings().removeClass('active');
}};
You can use: 您可以使用:
$("#menu a").click(function() {
//to remove class active from li elements
$(this).closest('ul').find('.active').removeClass('active');
//to remove li with active class
$(this).closest('ul').find('.active').remove();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.