具有相同名称和相同父级的div数,单独返回计数

时间:2017-10-11 19:39:41

标签: jquery

如何编写一个jquery代码,以便用类" aaa"来查找div的个别计数。在div和class" section-block" ? 我希望答案分别为4和3。 请帮忙

           <div class="section-block">
                            <div class="aaa"></div>
                            <div class="aaa"></div>
                            <div class="aaa"></div>
                            <div class="aaa"></div>
            </div>
            <div class="section-block">
                            <div class="aaa"></div>
                            <div class="aaa"></div>
                            <div class="aaa"></div>
            </div>

3 个答案:

答案 0 :(得分:0)

$('.section-block').map(function(){
    $(this).find('.aaa').length;
})

这适用于任意数量的区块。

答案 1 :(得分:0)

尝试以下内容。

$(document).ready(function() {
  $(".section-block").each(function() {
    var nbOfDivs = $(this).find(".aaa").length ;
    
    console.log(nbOfDivs) ;
  }) ;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section-block">
                <div class="aaa"></div>
                <div class="aaa"></div>
                <div class="aaa"></div>
                <div class="aaa"></div>
</div>
<div class="section-block">
                <div class="aaa"></div>
                <div class="aaa"></div>
                <div class="aaa"></div>
</div>

答案 2 :(得分:0)

// this gives total overall, result = 7
console.log( 
  $('.section-block').children('.aaa').length 
);

// one by one result = 4 and 3
$('.section-block').each(function(){
   console.log($(this).children('.aaa').length );
});

// this is for accessing of your interest
// result = 4
console.log(
  $('.section-block:eq(0)').children('.aaa').length
);

// 2nd one
// result = 3
console.log(
  $('.section-block:eq(1)').children('.aaa').length
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section-block">
  <div class="aaa"></div>
  <div class="aaa"></div>
  <div class="aaa"></div>
  <div class="aaa"></div>
</div>
<div class="section-block">
  <div class="aaa"></div>
  <div class="aaa"></div>
  <div class="aaa"></div>
</div>