2 回答

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>
注意:后代選擇器(空格)選擇所有的子孫。如果您只需要孩子,請使用孩子選擇器 (>)

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>
添加回答
舉報