如何在jquery中获取元素的子数组 [英] how to get children array of an element in jquery
问题描述
在这里,我想通过循环遍历它们来安排孩子们.
Heres my element, i want to arrange the children inside it by looping through them.
<div id="animDummy1">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
在这里,我想像代码看起来如何,但是children()当然不会返回孩子的数组
Heres how i imagine the code should look but children(), of course, doesn't return an array of the children
var children=$('#animDummy1').children();
for(var i=0;i<children.length;i++){
children[i].css('left',i*120+'px');
}
问题-我可以让子数组在循环中使用吗?我知道我可以为每个要执行的孩子附加一个函数,但是我可以在那里增加那个递增的"i"吗?
The question - can i get children array for use in a loop? I know i can attach a function for each of children to be executed on, but can i get that increasing "i" in there?
Thnx.
推荐答案
children()
返回类似于DOM节点数组的子代的jQuery对象.您的问题在循环内部-当您使用[]
访问单个对象时,您将获得没有css
方法的普通DOM节点.使用.eq(i)
或$(children[i])
.
children()
returns a jQuery object of the children which resembles an array of DOM nodes. Your problem is inside the loop - when you access individual objects with []
you get back plain DOM nodes which don't have a css
method. Either use .eq(i)
or $(children[i])
.
或者仅使用 each()方法,该方法无需手工编写for循环即可进行相同操作.阅读文档,了解如何获取回调中元素的索引.
Or just use the each() method, which lets you do the same without having to write a for loop by hand. Read the docs to find out how to get the index of the element inside the callback.
这篇关于如何在jquery中获取元素的子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!