我想知道是否有人有这样做的聪明方法:
我有一些动态生成的html,它会根据数据库生成一些div。
<div class="category_items">
<div class="category_item"></div>
<div class="category_item"></div>
<div class="category_item"></div>
</div>
如果这个数字大于 3,我需要隐藏那些多余的。当用户单击一个按钮时,它会显示隐藏的按钮,然后如果用户再次单击它们将再次消失。
这是我当前的 js 代码,它可以找到哪些 div 有很多 child (有效):
// Checks the number of items pr. category, if > 3, hide the rest of them
var categories = $categoriesDiv.children();
for (var i = 0; i < categories.length; ++i) {
var localCategoryItems = $('.category_items', categories[i]);
// Hide elements if length is > 3
if (localCategoryItems.children().length > 3) {
console.log('hide');
}
}
我只需要一种聪明的方法来隐藏和显示额外的 child 。谢谢!
最佳答案
您可以这样使用伪选择器 nth-child:
.category_items div:nth-child(n+4)
{
display: none;
}
此处提供示例:http://jsfiddle.net/AK4c2/1/
已更新:链接已更新,jQuery 可能如下所示:
$(".showhide").click(function()
{
$(".category_items div:nth-child(n+4)").toggle();
});
关于javascript - 如果子 div 的数量 > 3,则隐藏其余部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16937651/