2012-04-23 59 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

相關問題