3

我正在自定义一个 tumblr 博客,我想根据照片集中存在的照片数量应用某些样式和规则。当每个帖子具有相同的类时,我不确定如何计算每个帖子中存在的子元素的数量。如果这是 tumblr 生成的那种代码:

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

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

如何让 jQuery 返回第一个和第二个实例(即 2 和 3)中的元素数?

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

任何帮助将不胜感激!

干杯,斯科特

4

5 回答 5

7

您可以循环浏览每个照片集项目并分别计算其图像,然后在代码中使用该信息执行任何您想要的操作:

$(".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();
于 2012-04-23T16:40:00.290 回答
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
于 2012-04-23T16:40:07.737 回答
1

有几种方法可以解决这个问题。

首先,您可以使用.each()循环遍历每个.photoset

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

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

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

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

于 2012-04-23T16:41:03.963 回答
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
  }
});
于 2012-04-23T16:43:37.163 回答
0
$('.photoset:first img').length

$('.photoset:last img').length
于 2012-04-23T16:40:43.680 回答