亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅當子項存在時才隱藏元素

僅當子項存在時才隱藏元素

阿波羅的戰車 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 關注
  • 425 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號