2010-11-05 197 views
25

我有一个div与id ring-preview,它有一个非特定数img元素与stone-preview里面的类。jquery遍历子元素

我想遍历每个孩子的图像,并呼吁:

$(this).rotate(ring.stones[i].stone_rotation); 

this指的img元素和i指其div中的位置。

我该怎么做?

回答

49

您正在寻找.each() method
例如:

$('.ring-preview').children('img').each(function(i) { 
    $(this).rotate(ring.stones[i].stone_rotation); 
}); 

如果<img>元素不是直接的孩子,你将需要调用.find,而不是.children

8

您可以使用在这些情况下.each(),像这样:

$("#ring-preview img.stone-preview").each(function(i) { 
    $(this).rotate(ring.stones[i].stone_rotation); 
}); 

的第一个参数的回调函数是你之后的索引。

+0

哪里是'each'? – borisdiakur 2012-10-09 10:21:56

+0

@Lego - 失踪,显然:)修正! – 2012-10-09 13:55:11

5
$('#ring-preview img.stone-preview').each(function(idx, itm) { 
    $(itm).rotate(stones[idx].stone_rotation); 
}); 
+0

每个函数中的'idx'和'itm'都适用于我。 – 2016-11-01 08:41:44