2009-06-29 11 views
2

jQueryを初めて使用しています。JQueryの反復

私は、パネルのいくつかのdivs inn 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"はIDの 'panel'という要素内のすべてのdivを取得します。次に、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 
    }); 
})