如果有相同的父类名,我很难从父类名中计算子div的长度。例如,
<div class="main-div">
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
</div>
这是我的代码我想从每个父div中分别计算子div的长度,但我得到的是整个子类div的总数,即,我想只计算第一个父类子项然后输出将是4但我得到8.我需要单独改变它们并找到长度。
我的jquery是
var countdiv = $('.parent').children('.child').length;
if( countdiv > 1 ){
something here ..
}
答案 0 :(得分:2)
您需要迭代父 div
s
$( "div.parent" ).each( function(){
console.log( "number of children for " + $( this ).index() + "th parent div is " + $( this ).children( ".child" ).length )
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-div">
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
</div>
答案 1 :(得分:1)
您可以使用.each
功能
$('.parent').each(function(){
var countDiv = $(this).children('.child').length;
// do something here
});
现场演示here
有关.each
功能的更多信息,请访问here
答案 2 :(得分:0)
尝试使用此选择器来获得第一个孩子:
$(document).ready(function()
{
var countdiv = $('.main-div .parent:first-child').children('.child').length;
alert(countdiv);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-div">
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
</div>