Javascript 切换一个元素并将其余元素隐藏在同一包装器类下
jQuery:Javascript 切换一个元素并将其余元素隐藏在同一包装器类下,javascript,jquery,Javascript,Jquery,jQuery: $("#star_btn1").click(function() { $('#ca').toggle(); // I would like to hide everything EXCEPT CA under parent wrapper .allthestates }); <div class="allthestates"> <!-- there are div ids here with every 50 states, all states are
$("#star_btn1").click(function() {
$('#ca').toggle();
// I would like to hide everything EXCEPT CA under parent wrapper .allthestates
});
<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>
HTML:
$("#star_btn1").click(function() {
$('#ca').toggle();
// I would like to hide everything EXCEPT CA under parent wrapper .allthestates
});
<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
,然后单击下的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>
$(“#star_btn1”)。单击(函数(){
$('.allthestates>:不是(#ca)).hide();
$('#ca').show();
});
加利福尼亚
得克萨斯州
JQuery具有“not”函数,您可以调用该函数来排除任何您想要的元素
$("#star_btn1").click(function() {
$('.allthestates').children().not('#ca').toggle();
// I would like to hide everything EXCEPT CA under parent wrapper .allthestates
});
请看这里:
在Vohuman的帮助下,我们取得了更好的结果:
$(".allthestates > :not(#ca)").hide();
“>”选择器从第一个选择器中获取所有直接子项,我们从该集合中排除id为“#ca”的子项
$("#star_btn1").click(function() {
$('.allthestates').children().hide().filter('#ca').show();
});
中没有#ca
。所有状态均为。请显示所有HTML-无论如何,如果您以一个特定元素为目标并使用其ID,其他元素将不会受到影响。确定。我已经添加了它。$('#ca').show().sides().hide()
?是吗?如果在状态中添加一个类,例如.states
,那么您可以将它们作为一个组隐藏/显示,并单独隐藏/显示#ca
,即使它们位于同一父级下。如果您想使用id
制作50个按钮,这是个坏主意。看一个例子不,其他的东西都没有特定的类。我不能这样做,因为我将为每个州制作50个按钮。我必须创建更多的类来标识每个按钮的其他所有内容。not或not()操作符可以避免这些情况。为什么要进行向下投票?我在猜测一个非常模糊的HTML示例。我将其更改为在#ca
元素以外的所有元素上使用:not()选择器。嗨,@KJPrice先生,我否决了它,因为它是最糟糕的可伸缩性解决方案!但是你的修订版很棒!这里的:not
排除了一个。集合中没有ca
id的所有states
元素。@Vohuman你说得对,更正了我的代码。很抱歉,当前选择器没有太多意义,它从父集合中排除了一个子元素。怎么样:$(“.allthestates>:not(#ca)”).hide()
?@Vohuman我可能编辑得太快了。:)它确实有道理,以一种奇怪、抽象的方式但由于您的解决方案不那么抽象,因此我重新编辑了。:)