[jquery] jQuery를 사용하여 div의 하위 요소를 어떻게 반복합니까?

div가 있고 그 안에 여러 입력 요소가 있습니다 … 각 요소를 반복하고 싶습니다. 아이디어?



답변

children()및을 사용 each()하여 선택기를 선택적으로 전달할 수 있습니다.children

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

직계 자식 선택기를 사용할 수도 있습니다.

$('#mydiv > input').each(function () { /* ... */ });


답변

또한 특정 컨텍스트 내에서 모든 요소를 ​​반복하는 것이 가능합니다.

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

jQuery ‘input’Selector에 전달되는 두 번째 매개 변수 $ ( ‘# mydiv’)는 컨텍스트입니다. 이 경우 each () 절은 #mydiv의 직계 자식이 아닌 경우에도 #mydiv 컨테이너 내의 모든 입력 요소를 반복합니다.


답변

자식 요소를 재귀 적 으로 반복 해야하는 경우 :

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"));   

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


답변

이 방법으로도 수행 할 수 있습니다.

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


답변

$('#myDiv').children().each( (index, element) => {
    console.log(index);     // children's index
    console.log(element);   // children's element
 });

이것은 모든 자식을 반복하며 인덱스 값을 가진 요소는 각각 elementindex를 사용하여 개별적으로 액세스 할 수 있습니다 .


답변

children () 자체는 루프입니다.

$('.element').children().animate({
'opacity':'0'
});


답변

나는 당신이 사용해야한다고 생각하지 않는다. each()표준 for 루프를 사용할 수있다.

var children = $element.children().not(".pb-sortable-placeholder");
for (var i = 0; i < children.length; i++) {
    var currentChild = children.eq(i);
    // whatever logic you want
    var oldPosition = currentChild.data("position");
}

당신은 루프에 대한 표준을 수있는이 방법은 같은 기능 breakcontinue기본적으로 작동

또한 debugging will be easier