Jquery”;对于“;循环查找有多少孩子

Jquery "for" loop to find how many children

本文关键字:多少 查找 孩子 对于 Jquery 循环      更新时间:2023-09-26

我正试图用类".child"来提醒一个div中有多少个孩子。例如:一个div内部有五个".chil"。我不知道为什么我的for循环不起作用,我意识到有更好的方法,但我正在练习循环。谢谢问题可以在这里找到http://jqexercise.droppages.com/#page_0013_

for (var i = 1; i < 100; i++){
    if($(".child:nth-child(i)") == true){    
    }
    else {
      alert(i);
      break;      
    }
}

您可以在如下div中获得.child的编号。

var num = $('div').find('.child').length;
console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <span class="child">Child</span>
    <span class="child">Child</span>
    <span class="child">Child</span>
    <span class="child">Child</span>
    <span class="child">Child</span>
    <span class="child">Child</span>
</div>

更新:如果您想使用for循环,那么您可以使用jquery eq()函数如下所示。

for (var i = 0; i < 100; i++) {
    if ($('.child').eq(i).length) {
    }
    else {
        alert(i);
        break;
    }
}

您使用了i作为字符串。使用nth-child()执行以下操作。

for (var i = 1; i < 100; i++) {
    if ($(".child:nth-child(" + i + ")").length) {
    }
    else {
        alert(i-1);
        break;
    }
}

另一种方式:

alert($('div .child').length);

i内部,如果条件是字符串而不是变量,则执行以下操作:

if ( $( ".child:nth-child(" + i + ")" ) == true )
var intChildrenCount = $("div .child").length;
var arrChildren = $("div .child");
$.each(arrChildren,function(){
   // Here you will get child's HTML one by one
   console.log($(this).html());
});