计算父类中的特定子类

Counting specific children within parent div

本文关键字:子类 父类 计算      更新时间:2023-09-26

我目前正在尝试显示库中图像数量的计数(即"此库中有'x'个图像")。每个页面上都有多个库,因为它们嵌入到Wordpress提要中的帖子中。

在我的localhost上,我实际上可以让它显示计数,但它会对页面上的每个图像进行计数,就好像它不受父div的限制一样。

任何投入都将不胜感激——http://jsfiddle.net/fvoLaad1/2/或以下代码:

编辑:感谢@Mohamed Yousef和@Tom Millard解决-此处为工作版本http://jsfiddle.net/kuLsjLgg/

jQuery

jQuery(function($) {
  $('.iso-post').each(function(i) {
    var n = $('.gallery-item').length;
    $(".image-count").text("There are " + n + " images in this gallery.");
  });
});

HTML

<li class="iso-post">
    <span class="image-count"></span>
    <div class="post-content">
        <div class="gallery">
            <figure class="gallery-item">IMG</figure>
            <figure class="gallery-item">IMG</figure>
            <figure class="gallery-item">IMG</figure>
        </div>
    </div>
</li>
<li class="iso-post">
    <span class="image-count"></span>
    <div class="post-content">
        <div class="gallery">
            <figure class="gallery-item">IMG</figure>
            <figure class="gallery-item">IMG</figure>
            <figure class="gallery-item">IMG</figure>
            <figure class="gallery-item">IMG</figure>
            <figure class="gallery-item">IMG</figure>
        </div>
    </div>
</li>

您需要循环浏览每个图库以获得中的图像数量

jQuery(function($) {
   $('.gallery').each(function(){
    var n = $(this).find('.gallery-item').length;
    $(this).closest('.iso-post').find(".image-count").text("There are " + n + " images in this gallery.");
   });
});

工作演示

要获得所有图像的长度,只需使用

$('.gallery-item').length

您需要使用this来引用当前循环索引,使用find来定位子级。

jQuery(function($) {
  $('.iso-post').each(function(i) {
    var n = $(this).find('.gallery-item').length;
    $(this).find(".image-count").text("There are " + n + " images in this gallery.");
  });
});