繁体   English   中英

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

[英]Hide element only if child exists

具有不同数量子元素的多个父元素,例如:

<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>

几乎可以用这个解决:

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

它在父母双方中隐藏第二个 div,但它应该只隐藏在第一个父母中,因为第二个父母没有第三个孩子。

使用 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>

使用 Jquery

$(".items div")选择所有子 div。 所以你可以使用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>

注意:后代选择器(空格)选择所有子代和孙代。 如果您只需要孩子使用子选择器 (>)

您的选择器正在抓取文档中的所有.items ,因此它几乎总是会隐藏第二个。

相反,您希望分别评估每个项目的子项,以确定它是否应该隐藏。

见下面的演示代码

 $(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