我有一个带有许多图像的 div。现在每个图像都有一个类,并且许多图像具有相同的类。现在我想遍历每个图像,收集它的类并计算具有特定类的图像数量......
HTML:
<div id="articleThumb">
<ul id="makeThumb">
<li>
<img class="merc" src="../img/items/merc_sedan.jpg" />
</li>
<li>
<img class="merc" src="../img/items/merc_sedan2.jpg" />
</li>
<li>
<img class="bmw" src="../img/items/bmw_sedan.jpg" />
</li>
<li>
<img class="bmw" src="../img/items/bmw_hatchback.jpg" />
</li>
<li>
<img class="bmw" src="../img/items/bmw_sedan3.jpg" />
</li>
<li>
<img class="ford" src="../img/items/ford_sedan.jpg" />
</li>
<li>
<img class="ford" src="../img/items/ford_hatchback.jpg" />
</li>
<li>
<img class="ford" src="../img/items/ford_bakkie.jpg" />
</li>
<li>
<img class="ford" src="../img/items/ford_suv.jpg" />
</li>
<li>
<img class="mit" src="../img/items/mit_sedan.jpg" />
</li>
<li>
<img class="merc" src="../img/items/merc_suv.jpg" />
</li>
<li>
<img class="bmw" src="../img/items/bmw_suv.jpg" />
</li>
<li>
<img class="bmw" src="../img/items/bmw_suv2.jpg" />
</li>
<li>
<img class="mit" src="../img/items/mit_suv.jpg" />
</li>
<li>
<img class="mit" src="../img/items/mit_bakkie.jpg" />
</li>
</ul>
</div>
现在我知道我可以使用:
$('.bmw').length;
计算 .bmw 类的图像数量,但如果你有 300 个类,那效率就不高了。
我想做的是用jQuery(不是我指定的)确定类并像这样计算它:
$('#articleThumb ul li img').each(function () {
var y = $(this).attr('class');
var allClasses = [y];
});
现在计算所有类并将每个类的计数附加到其匹配的显示 div...
var countEachClass = allClasses.length;
$(countEachClass).appendTo('#count .' + [y]);
<div id="count">
<div class="bmw">number calculated by .length</div>
<div class="merc">number calculated by .length</div>
<div class="ford">number calculated by .length</div>
...etc
</div>
更新: 我想用以下内容替换#count div以显示数字:
<article class="make">
<div class="content">
<h4><a class="merc" href="#latestClick">Mercedes-Benz</a></h4>
<div class="date">12 March 2013</div>
<div class="count">THE NUMBER HERE</div>
</div>
</article>
<article class="make latest">
<div class="content">
<h4><a class="bmw" href="#latestClick">BMW</a></h4>
<div class="date">12 March 2013</div>
<div class="count">THE NUMBER HERE</div>
</div>
</article>
答案:http: //jsfiddle.net/YNqGR/9/