2010-06-11 3 views

답변

370

사용 children()each(), 당신은 선택적으로 당신은 또한 단지 바로 아이 선택기를 사용할 수 children

$('#mydiv').children('input').each(function() { 
    alert(this.value); // "this" is the current element in the loop 
}); 

에 선택기를 전달할 수 있습니다 특정 상황에서 얼마나 깊이 중첩되었는지는 중요하지 않습니다.

$('input', $('#mydiv')).each(function() { 
    console.log($(this)); //log every element found to console output 
}); 

jQuery 'input'Selector로 전달되는 두 번째 매개 변수 $ ('# mydiv')는 컨텍스트입니다. 이 경우 each() 절은 #mydiv의 직접 하위 항목이 아니더라도 #mydiv 컨테이너 내의 모든 입력 요소를 반복합니다.

+52

다음 클로저에서 $ (this)를 사용하여 루프의 "현재"항목에 액세스하십시오. – amarsuperstar

+1

@amarsuperstar : 그 정보를 추가하는 과정에있었습니다 :-) –

+0

$ (this)가 부모의 "n"번째 자식이라고 가정하고 "n"값을 알 수있는 방법이 있습니까? –

40

모든 요소를 ​​반복하는 것도 가능합니다 :

+1

아마도 중첩 때문에이 솔루션은 저에게 효과적 이었지만 다른 솔루션은 그렇지 못했습니다. 그런 이유로 나는 이것이 보통 더 나은 해결책이라고 생각할 것이다. – arame3333

2

당신은 자식 요소를 통해 루프 필요 반복적으로 경우

function recursiveEach($element){ 
    $element.children().each(function() { 
     var $currentElement = $(this); 
     //////////// Show element 
     console.info($currentElement); 
     //////////// Show events handlers of current element 
     console.info($currentElement.data('events')); 
     //////////// Loop her children 
     recursiveEach($currentElement); 
    }); 
} 

//////////// Parent div 
recursiveEach($("#div")); 

참고 :이 예에서 내가 객체에 등록 이벤트 핸들러를 보여줍니다.

2

그렇게 할 수도 있습니다.
$('input', '#div').each(function() { console.log($(this)); //log every element found to console output });

관련 문제