切换一个元素并将其余元素隐藏在同一包装类下

toggle one element and hide the rest under same wrapper class

本文关键字:元素 隐藏 包装类 余元素 一个      更新时间:2023-09-26

jQuery:

$("#star_btn1").click(function() {
$('#ca').toggle();
// I would like to hide everything EXCEPT CA under parent wrapper .allthestates 
});

HTML:

<div class="allthestates">
<!-- there are div ids here with every 50 states, all states are display none in css by default, the problem is the JS -->
<div id="ca">content</div>
</div>

因此,单击按钮#star_btn1,然后显示.allthestates下的id #ca——其他一切都不会。

尝试":not()"选择器和">"(直属子项),您可以执行以下操作:

$("#star_btn1").click(function() {
    $('.allthestates > :not(#ca)').hide();
    $('#ca').show();
});
<div class="allthestates">
   <div class="state" id="CA">California</div>
   <div class="state" id="TX">Texas</div>
</div>
JQuery有一个"not"函数,您可以调用它来排除任何您想要的元素。
$("#star_btn1").click(function() {
$('.allthestates').children().not('#ca').toggle();
// I would like to hide everything EXCEPT CA under parent wrapper .allthestates 
});

试试这个

$("#star_btn1").click(function() {
    $('.allthestates').children().hide().filter('#ca').show();
});

看看这里:http://www.w3schools.com/jquery/sel_not.asp

$(".allthestates:not(.allthestates #ca)").hide();

在Vohuman的帮助下,我们得到了更好的结果:

$(".allthestates > :not(#ca)").hide();

">"选择器从第一个选择器中获取所有直接子项,并从该集合中排除id为"#ca"的子项。