2009-06-29 41 views
2

我是jQuery的新手。JQuery中的迭代

我在我的代码中有一个变量增量,它显示了面板中有多少个divs mne。

我想迭代通过这些div来获取标签的属性,输入类型,尺寸每个div内的所有东西。

从1开始,我想迭代增量..我如何在JQUery中这样做?请给我一个建议。

回答

4

如果你想通过在JQuery的一个小组的所有div迭代那么最简单的方法是简单地做到以下几点:

$("#panel div").each(function() { 
    // $(this) refers to the div 
} 

如果你想这个限制至第一N div的则有无数的方法来做到这一点:

$("#panel div:lt(" + (N+1) + ")").each(function() { 
    // limits to the only those div's less than N+1. 
} 
2

我会跟着samjudson说,但有一些更详细说明。

首先,选择器“#panel div”获取元素中的所有div,其ID为'panel',这听起来像你想要的。然后,使用jQuery的'each'函数,您可以调用任意函数,并将每个div绑定到'this'项目。

所以在函数中,“this”实际上是DOM中每个div的项目。通过引用$(this),您可以获得jQuery在项目上进行交互的力量 - 但是如果您只需要DOM项目本身的裸机属性,则可以从“this”直接获取它们。

$('#panel div').each(function(i) { 
    // 'this' is the div, i is an incrementing value starting from 0, 
    // per zero-based JS norms 
    // If you're going to do a lot of jQuery work with the div, 
    // it's better to make the call once and save the results - more efficient 
    var $this = $(this); 

    // If you want to get out before you're done processing, 
    // simply return false and it'll stop the looping, like a break would 
    if (i > 4) { return false; } 

    // Look up the labels inside of the div 
    // Note the second argument to the $ function, 
    // it provides a context for the search 
    $("label", this).each(function(){ 
     // 'this' is NOW each label inside of the div, NOT the div 
     // but if you created a $this earlier, you can still use it to get the div 
     // Alternately, you can also use $(this).parent() 
     // to go up from the label to the div 
    }); 
})