2009-06-29 7 views
2

jQuery를 처음 사용했습니다.JQuery의 반복

내 코드에서 패널의 몇개의 여백을 표시하는 변수가 증가하고 있습니다.

각 div 내에서 레이블, 입력 유형, 크기 등의 속성을 얻기 위해 해당 div를 반복하고 싶습니다.

1에서 시작하여 최대 증가까지 반복하고 싶습니다. JQuery에서 어떻게 할 수 있습니까? 제게 제안 해주세요.

답변

4

당신은 단순히 다음을 수행하는 것입니다 후 JQuery와의 패널에있는 모든 div를 통해 가장 쉬운 방법을 반복하려면 : 당신이 거기에 다음 첫 번째 N div의이을 제한하려면

$("#panel div").each(function() { 
    // $(this) refers to the 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 
    }); 
})