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