继承我的元素,我想通过循环它们来安排孩子们.
<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循环就可以执行相同的操作.阅读文档以了解如何获取回调内元素的索引.
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)
使用 jQuery 的其他答案children().each()
可能对大多数情况都有帮助。但是,如果您确实需要一个实际的 javascript 数组,您可以执行以下操作:
var childrenArray = $('#animDummy1').children().toArray();
Run Code Online (Sandbox Code Playgroud)
这将允许您拥有一个真正的数组,可在循环中或与需要数组作为参数的其他函数一起使用。
归档时间: |
|
查看次数: |
72442 次 |
最近记录: |