/ / JQueryの反復 - jquery、イテレーター、foreach

JQueryの反復 - jquery、iterator、foreach

私はjQueryが初めてです。

私は自分のコードに可変のインクリメントを持っています。これはパネルの中にいくつのdivがあるかを示しています。

ラベルのプロパティ、入力タイプ、各div内のサイズをすべて取得するために、これらのdivを繰り返し処理したいと思います。

1から始めて、インクリメントするまで繰り返します。JQUeryではどうすればよいですか。私に提案をお願いします。

回答:

回答№1は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については2

私はsamjudsonが言ったことと一緒に行きますが、もう少し詳しく説明します。

まず、セレクタ "#panel div"はすべての要素を取得します。"panel"というIDを持つ要素内のdivは、あなたが望むもののように聞こえます。次に、jQueryの "e​​ach"関数を使用して、各divを "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
});
})