简体   繁体   English

仅当子元素存在时隐藏元素

[英]Hide element only if child exists

Multiple parent with different amount of child elements, eg:具有不同数量子元素的多个父元素,例如:

<div class="items">
  <div></div>
  <div>hide this child</div>
  <div></div>
</div>

<div class="items">
  <div></div>
  <div>don't hide this child</div>
</div>

Can be almost solved with this:几乎可以用这个解决:

if ($(".items div:nth-child(3)").length) {
    $(".items div:nth-child(2)").hide();
}

It hides the second div in both parents, but it should hide only in first parent, because second parent doesn't have a third child.它在父母双方中隐藏第二个 div,但它应该只隐藏在第一个父母中,因为第二个父母没有第三个孩子。

Using CSS last-child使用 CSS last-child

 .items div:nth-child(2):not(:last-child) { display: none; }
 <div class="items"> <div></div> <div>hide this child</div> <div></div> </div> <div class="items"> <div></div> <div>don't hide this child</div> </div>

Using Jquery使用 Jquery

$(".items div") selects all child div. $(".items div")选择所有子 div。 So you can use each() to select child from different parent所以你可以使用each()从不同的父母中选择孩子

 $(".items").each(function() { if ($("div", this).length > 2) { $("div:nth-child(2)", this).hide(); } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="items"> <div></div> <div>hide this child</div> <div></div> </div> <div class="items"> <div></div> <div>don't hide this child</div> </div>

Note: descendant selector (space) selects all both children and grandchildren.注意:后代选择器(空格)选择所有子代和孙代。 If you need only children use child selector (>)如果您只需要孩子使用子选择器 (>)

Your selector is grabbing all .items in the document so it's pretty much always going to hide the second one.您的选择器正在抓取文档中的所有.items ,因此它几乎总是会隐藏第二个。

Instead, you want to evaluate the children of each item separately to determine if it should be hidden or not.相反,您希望分别评估每个项目的子项,以确定它是否应该隐藏。

See demo code below见下面的演示代码

 $(function() { // get all the items var items = $(".items"); // check their children, if more than 2 children, hide them $.each(items, function(idx, item) { if ($(item).children().length > 2) { $(item).hide(); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="items"> <div></div> <div>hide this child</div> <div></div> </div> <div class="items"> <div></div> <div>don't hide this child</div> </div>

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

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