如何迭代for循环的孩子 [英] How to iterate over children with for-loop

查看:232
本文介绍了如何迭代for循环的孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想迭代jQuery的 .children()返回值的所有子元素,如下所示:

  var childs = $ element.children(); 
for(var i = 1; i< childs.length - 1; i ++)
childs __。foo();

我必须在3行写入,而不是 __ ,来访问第i个孩子?

我希望这个因为我想访问第(i-1)和第(i + 1) ) - 循环中的子节点,如下所示:

  var childs = $ element.children(); 
for(var i = 1; i< childs.length-1; i ++)
{
childs< i>> .css('height',childs< i-1>> .height());
childs< i>> .css('width',childs< i + 1>> .width());



$ b所以我假设 each() c code code code $是$ javascript数组。所以你可以通过 childs [indexOfElement] 访问数组中的对象。在你的情况 childs [i]

  var childs = $ element 。儿童(); 
for(var i = 1; i< childs.length - 1; i ++)
childs [i] .foo();

  var childs = $ element.children(); 
for(var i = 1; i< childs.length - 1; i ++)
{
childs [i] .css('height',childs [i-1] .height ());
childs [i] .css('width',childs [i + 1] .width());

BUT :您的代码有错误。来自children集合的元素不是一个jQuery对象。这只是一个DOM元素。所以你必须把它们包装在 $(...)中来使用jQuery函数。所以你的代码将变成:

$ $ p $ $ $ $ $ $ $ var childs = $ element.children();
for(var i = 1; i< childs.length - 1; i ++)
{
var thisElement = $(childs [i]);
var next = $(childs [i + 1]);
var prev = $(childs [i-1]);
thisElement.css('height',prev.height());
thisElement.css('width',next.width());
}

PS。它应该被命名为 children 。 :)

I want to iterate over all childs of a jQuery's .children() return value, like this:

var childs = $element.children();        
for (var i = 1; i < childs.length - 1; i++)
    childs__.foo();

What do I have to write in the 3 line instead of __, to access the i-th child?

I want this becaus I want to access the (i-1)-th and (i+1)-th child in the loop, like this:

var childs = $element.children();        
for (var i = 1; i < childs.length - 1; i++)
{
    childs<<i>>.css('height', childs<<i - 1>>.height());
    childs<<i>>.css('width', childs<<i + 1>>.width());
}

So I assume the each() function will not work.

解决方案

childs is a javascript array. So you access objects within the array by childs[indexOfElement]. In your case childs[i].

var childs = $element.children();        
for (var i = 1; i < childs.length - 1; i++)
    childs[i].foo();

and

var childs = $element.children();        
for (var i = 1; i < childs.length - 1; i++)
{
    childs[i].css('height', childs[i-1].height());
    childs[i].css('width', childs[i+1].width());
}

BUT: Your code has an error. The element from the children collection is NOT a jQuery object. It's just an DOM element. So you have to wrap them in $(...) to use jQuery functions. So your code will become:

var childs = $element.children();        
for (var i = 1; i < childs.length - 1; i++)
{
    var thisElement = $(childs[i]);
    var next = $(childs[i+1]);
    var prev = $(childs[i-1]);
    thisElement.css('height', prev.height());
    thisElement.css('width', next.width());
}

PS. It should be named children. :)

这篇关于如何迭代for循环的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆