2010-12-03 15 views
77

私は、リスト内のオプションをループにjQuery .each()インデックス?

$('#list option').each(function(){ 
//do stuff 
}); 

を使用しています。 現在のループのインデックスをどのように取得できるのでしょうか?

私はvar i = 0を持つ必要がありません。 ループ内にはi ++があります。

+7

.each構文*ない、APIを読んで、おそらく... http://api.jquery.com/each/ –

答えて

134
$('#list option').each(function(index){ 
    //do stuff 
    alert(index); 
}); 

アラート指数:)

+1

と*、等価のネイティブメソッド 'forEach'や他の普及しているAPIと同様に、' function(value | element、index | key) 'などのように、 – Barney

+3

alertよりもconsole.logを使用してデバッグすることがよくあります。大規模なオプションリストは、アラートを持つウィンドウスタックを台無しにするでしょう。 – MarkokraM

25

jQueryのあなたのためにこれの世話をします。 .each()コールバック関数の最初の引数は、ループの現在の反復のインデックスです。第二は、だから、DOM要素を、現在一致している:jQuery.each() documentationから

$('#list option').each(function(index, element){ 
    alert("Iteration: " + index) 
}); 
3
$('#list option').each(function(intIndex){ 
//do stuff 
}); 
9

を:

.each(function(index, Element)) 
    function(index, Element)A function to execute for each matched element. 

だから、あなたが使用したいと思う:

$('#list option').each(function(i,e){ 
    //do stuff 
}); 

...どこindexはインデックスになり、要素はリストのオプション要素になります

1

このシンタックスはありません。データ収集や

jQuery.each(collection, callback(indexInArray, valueOfElement)); 

OR

jQuery.each(jQuery('#list option'), function(indexInArray, valueOfElement){ 
//your code here 
});