计算父类中的特定子类
Counting specific children within parent div
我目前正在尝试显示库中图像数量的计数(即"此库中有'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.");
});
});
相关文章:
- 是否可以从父类访问子类的属性
- 子类访问父类's闭包变量
- 如何通过Prototype或jquery移除子类的父类基类
- JavaScript—父类和子类/对象的此问题
- 如何在单击父类的另一个子类时获取子类的值
- hover添加类-或子类:悬停以影响父类
- jQuery父类更改的子级
- 如果类中没有子元素,则赋予父类
- 创建新的子类对象时设置父类中定义的变量时出现问题
- 如何从子类访问父类属性
- Jquery - 将父类添加到子类中的链接
- Ext.window 在父类中窗口的关闭按钮上覆盖子类中的销毁
- 在 dojo 中使用它通过父类访问子方法
- 如何定位父类和子类 I javascript
- 如何在 javascript 中从子原型调用父类的构造函数方法
- ECMAScript 6子类使用父类名称打印
- 如何在Cocos2dJS中将父类Sprite强制转换为子类MySprite
- RxJS 5子类Observable-静态方法返回父类的实例
- 如何基于子元素将类添加到父元素's类使用jQuery
- 使用jQuery更改select时更改父类父类