简体   繁体   English

这个2线jquery可以缩短为1线吗?

[英]Can this 2-liner jquery be shortened to 1 line?

I have these divs, each have the same class .onediv and distinct ids div1, div2, div3我有这些 div,每个都有相同的 class .onediv和不同的 ids div1, div2, div3

<div class="alldivs">
   <div class="onediv" id="div1">
   </div>
   <div class="onediv" id="div2">
   </div>
   <div class="onediv" id="div3">
   </div>
</div>

I want to use jquery to change their css display property so that all of them are display none except id=div2 which is display block .我想使用 jquery 来更改他们的 css display属性,以便除id=div2这是display block之外,所有这些都display none Right now I'm doing it this way with 2 lines.现在我用 2 条线这样做。 Is there a quicker way to do the same thing with one line only?有没有更快的方法只用一条线做同样的事情?

$('.onediv').css('display', 'none');    
$('#div2').css('display', 'block');

If you're hiding/showing amongst siblings then the most generic (and still performant) solution is to use .siblings() , like this:如果您在兄弟姐妹中隐藏/显示,那么最通用(并且仍然有效)的解决方案是使用.siblings() ,如下所示:

$("#div2").show().siblings().hide();

Note that .show() and .hide() are shortcuts for setting the display CSS property like you want here (between none and what it was before, block in the default <div> case).请注意, .show()和 .hide( .hide()是设置display CSS 属性的快捷方式,就像您在此处想要的那样(在none和之前的属性之间,在默认的<div>情况下block )。

$('.onediv:not(#div2)').css('display', 'none');

it is possible using filter function, but not recommended for performance reason:可以使用filter function,但出于性能原因不推荐:

$('.onediv').hide().filter('#div2').show();

$('#div2').siblings().css('display', 'none'); $('#div2').siblings().css('display', 'none');

Here is a creative one (but not necessarily useful):这是一个有创意的(但不一定有用):

$(".alldivs > div:even").hide();

Here is another one:这是另一个:

$(".onediv:not(:eq(1))").hide();

This code expects that by default your divs are not hidden (ie. no display:none in your css)此代码期望默认情况下您的 div 不隐藏(即在您的 css 中没有显示:无)

Try this:尝试这个:

$('.onediv').not('.onediv:last-child').css('display', 'none');    

Please don't downrank.请不要降级。 this works: check here: http://jsfiddle.net/ASBcg/这个工作:在这里检查: http://jsfiddle.net/ASBcg/

EDIT: If you want explicitly show that div this would be better:编辑:如果你想明确显示 div 这会更好:

$('.onediv').css('display', 'block').not('.onediv:last-child').css('display', 'none');    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM