2012-04-23 60 views
2

我正在自定义一个tumblr博客,并且我想根据photoset中存在的照片的数量应用某些样式和规则。我不确定每篇文章是否有相同的课程时,如何计算每篇文章中的子元素。如果这是由tumblr生成的代码排序:从一个类的实例中获取子元素的数量

<div class="photoset"> 
    <img /> 
    <img /> 
</div> 

<div class="photoset"> 
    <img /> 
    <img /> 
    <img /> 
</div> 

如何让jQuery来恢复第一和第二实例(即2和3)元素的数量?

我试过使用$('.photoset img').length();,这给了我所有存在的元素(即在这种情况下是5)的总数。

任何帮助将不胜感激!

干杯, 斯科特

回答

6

您可以通过每个photoset项目周期又算什么单独的图像,然后做任何你想要在代码中的那一点信息:

$(".photoset").each(function(index, elem) { 
    var numImages = $(this).find("img").length; 
    // do whatever processing you wanted to with numImages here 
}); 

如果你想把这些计数在数组中,你可以做这样的:

var imgCountArray = $(".photoset").map(function() { 
    return($(this).find("img").length) 
}).get(); 
+0

这是完美的,非常感谢你的快速回复! – sowasred2012 2012-04-23 16:50:41

2

下面尝试,

var imgCounts = []; 

$('.photoset').each (function() { 
    imgCounts.push($(this).find('img').length); 
}); 

现在,

imgCounts[0] = 2 //first divs img count 
imgCounts[1] = 3 //second divs img count 
0
$('.photoset:first img').length 

$('.photoset:last img').length 
+0

如果有两张以上的照片,这不会有太大帮助。 – 2012-04-26 19:44:26

1

有几个方法,你可以去这个问题。

首先,你可以使用.each()循环通过每个.photoset

$('.photoset').each(function() { 
    var num = $(this).find('img').length; 
    // Do something based on num 
}); 

或者,使用.eq():eq()选择某一个:

var num = $('.photoset:eq(1) img').length;

var num = $('.photoset').eq(1).find('img').length;

1

你可以使用:

$(".photoset").each(function(i, photoset) { 
    photoset = $(photoset); 
    var numImages = photoset.children().length; 
    // or var numImages = photoset.find("img").length; for only images 

    if (numImages === 2) { 
    // your code 
    } 
    if (numImages === 3) { 
    // your code 
    } 

    // or just comparing whether greater or lower 
    if (numImages > 2) { 
    // your code 
    } 
}); 
+0

一旦我学会了如何计数,这就是我想要的方式 - 这是一个巨大的帮助,谢谢! – sowasred2012 2012-04-23 16:52:18

+0

欢迎您:) – 2012-04-23 16:52:52

相关问题