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

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


<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,但它应该只隐藏在第一个父母中,因为第二个父母没有第三个孩子。


阿波罗的战车
浏览 205回答 2
2回答

MYYA

使用 CSS last-child.items div:nth-child(2):not(:last-child) {&nbsp; display: none;}<div class="items">&nbsp; <div></div>&nbsp; <div>hide this child</div>&nbsp; <div></div></div><div class="items">&nbsp; <div></div>&nbsp; <div>don't hide this child</div></div>使用 Jquery$(".items div")选择所有子分区。所以你可以用来each()从不同的父母中选择孩子$(".items").each(function() {&nbsp; if ($("div", this).length > 2) {&nbsp; &nbsp; $("div:nth-child(2)", this).hide();&nbsp; }})<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="items">&nbsp; <div></div>&nbsp; <div>hide this child</div>&nbsp; <div></div></div><div class="items">&nbsp; <div></div>&nbsp; <div>don't hide this child</div></div>注意:后代选择器(空格)选择所有的子孙。如果您只需要孩子,请使用孩子选择器 (>)

12345678_0001

您的选择器正在抓取文档中的所有内容 .items,因此它几乎总是会隐藏第二个。相反,您想分别评估每个项目的子项以确定它是否应该隐藏。见下面的演示代码$(function() {&nbsp; // get all the items&nbsp; var items = $(".items");&nbsp; // check their children, if more than 2 children, hide them&nbsp; $.each(items, function(idx, item) {&nbsp; &nbsp; if ($(item).children().length > 2) {&nbsp; &nbsp; &nbsp; $(item).hide();&nbsp; &nbsp; }&nbsp; });});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="items">&nbsp; <div></div>&nbsp; <div>hide this child</div>&nbsp; <div></div></div><div class="items">&nbsp; <div></div>&nbsp; <div>don't hide this child</div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript