为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

阿波罗的战车 2023-05-25 16:42:44
具有不同数量子元素的多个父级,例如:<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,但它应该只隐藏在第一个父母中,因为第二个父母没有第三个孩子。
查看完整描述

2 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

使用 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")选择所有子分区。所以你可以用来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>

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



查看完整回答
反对 回复 2023-05-25
?
12345678_0001

TA贡献1802条经验 获得超5个赞

您的选择器正在抓取文档中的所有内容 .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>


查看完整回答
反对 回复 2023-05-25
  • 2 回答
  • 0 关注
  • 193 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信