2010-12-03 5 views
77

나는 목록의 옵션을 통해 루프jQuery .each() 인덱스?

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

을 사용하고 있습니다. 현재 루프의 인덱스를 얻는 방법을 궁금합니다.

나는 var i = 0을 갖고 싶어한다. 그리고 루프 내부에는 ++가 있습니다.

+7

API를 읽기와

.each 구문, 아마도 ... http://api.jquery.com/each/ –

답변

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

경고 색인 :

+1

그리고 *하지 * 예를 들어'function (value | element, index | key)'와 같은 원시 메소드'forEach'와 다른 모든 대중적인 API를 사용합니다. – 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)); 

또는

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