jquery 迭代子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4109376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:41:31  来源:igfitidea点击:

jquery iterate over child elements

jquery

提问by JD Isaacks

I have a divwith the id ring-preview, it has a unspecifed number of imgelements with the class stone-previewinside it.

我有一个divid ring-preview,它有一个未指定数量的img元素,其中包含类stone-preview

I would like to iterate over each of these child images and call:

我想遍历每个子图像并调用:

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

Where thisrefers the imgelement and irefers to its position within the div.

wherethis指的是img元素,i指的是它在div.

How can I do that?

我怎样才能做到这一点?

回答by SLaks

You're looking for the .each()method.
For example:

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

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

If the <img>elements aren't direct children, you'll need to call .findinstead of .children.

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

回答by Nick Craver

You can use a .each()in these cases, like this:

您可以.each()在这些情况下使用 a ,如下所示:

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

The first parameter to the callback function is the index you're after.

回调函数的第一个参数是您要查找的索引。

回答by Agent_9191

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