如何在jquery中获取子元素的数组

Mar*_*tin 21 jquery

继承我的元素,我想通过循环它们来安排孩子们.

<div id="animDummy1">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
Run Code Online (Sandbox Code Playgroud)

下面我想象代码看起来如何,但是当然,children()不会返回一个孩子的数组

var children=$('#animDummy1').children();
for(var i=0;i<children.length;i++){
    children[i].css('left',i*120+'px');
}
Run Code Online (Sandbox Code Playgroud)

问题 - 我可以在循环中使用子数组吗?我知道我可以附上每个要执行对儿童的功能,但我可以在那里"我"增加?

日Thnx.

Mat*_*nen 30

children()返回子节点的jQuery对象,类似于DOM节点数组.你的问题在循环内 - 当你访问单个对象时,[]你得到了没有css方法的普通DOM节点.要么使用.eq(i)$(children[i]).

或者只使用each()方法,这样您无需手动编写for循环就可以执行相同的操作.阅读文档以了解如何获取回调内元素的索引.

  • 这不是真的正确 - "children()"返回一个jQuery对象而不是一个数组.它确实有jQuery.each()可以使用的"索引",但它不是类型数组.如果你想获得一个实际的数组,请尝试使用`children().toArray()`.要确认这一点,请尝试使用`children()实例的Array`与`children().toArray()instanceof Array` :) (2认同)

the*_*imp 11

这是正确的方法.

var children=$('#animDummy1').children();

children.each(function(idx, val){
   $(this).css('left',idx*120+'px');
});
Run Code Online (Sandbox Code Playgroud)

或者实际上这更好.

$('#animDummy1').children().each(function(idx, val){
   $(this).css('left',idx*120+'px');
})
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 8

使用 jQuery 的其他答案children().each()可能对大多数情况都有帮助。但是,如果您确实需要一个实际的 javascript 数组,您可以执行以下操作:

var childrenArray = $('#animDummy1').children().toArray();
Run Code Online (Sandbox Code Playgroud)

这将允许您拥有一个真正的数组,可在循环中或与需要数组作为参数的其他函数一起使用。