如何显示特定数量的子div?

时间:2015-08-05 18:01:32

标签: javascript jquery html

我不确定这是否可行...... 如果你有f.ex。

<div id="parent">
    <div id="child1"></div>
    <div id="child2"></div>
    <div id="child3"></div>
    <div id="child4"></div>
    <div id="child5"></div>
    <div id="child6"></div>
</div>

你怎么能用jquery或javascript(或其他任何东西),只显示前两个?

5 个答案:

答案 0 :(得分:2)

您可以使用:gt() jQuery selector

$("#parent>div:gt(1)").hide()

实际上,如果您想逐步显示,最好先隐藏所有内容,然后使用:lt() jQuery selector进行展示。

$("#parent>div").hide();

var n = 2;
$("#parent>div:lt(" + n + ")").show();

el.click(function () {
    n += 5;
    $("#parent>div:lt(" + n + ")").show();
});

答案 1 :(得分:1)

您可以使用CSS执行此操作:

#parent div:nth-child(n+3) {
    display: none;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/%3Anth-child

JsFiddle

答案 2 :(得分:0)

这是你在jQuery中可以做到的一种方式:

// hide all the children
$("#parent>div").hide();
// unhide the two we care about
$("#child1").show();
$("#child2").show();

如果您没有已知的元素ID,这里有一个更通用的解决方案:

$("#parent>div~div~div").hide();

答案 3 :(得分:0)

您可以像这样编写jQuery代码:

var visibleIndexes = [0, 1]
$("#parent").children().each(function(index) {
 if(visibleIndexes.indexOf(index) === -1){
   $(this).hide();
 } else {
   $(this).show();
 }
}); 

您可以存储要在变量visibleIndexes中显示的索引或任何其他变量,并将其传递给此函数

答案 4 :(得分:0)

一种简单的迭代方法:

$( document ).ready(function() {
    var i = 0;
    var somevalue = 3;
    $("#parent").children("div").each(
        function () {
            if(i > somevalue) $(this).hide();
            i++;
        });
});