codememo

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

tipmemo 2023. 5. 23. 21:55
반응형

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

저는 디브를 가지고 있고, 그 안에 몇 가지 입력 요소가 있습니다.저는 각각의 요소들을 반복하고 싶습니다.아이디어?

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

$('#parentid').children('.childclass').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')가 컨텍스트입니다.이 경우 각() 절은 #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"));   

참고: 이 예에서는 개체에 등록된 이벤트 처리기를 보여 줍니다.

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

이것은 모든 하위 항목을 통해 반복되며 인덱스 값을 가진 요소는 각각 요소와 인덱스를 사용하여 개별적으로 액세스할 수 있습니다.

다음과 같은 방법으로도 수행할 수 있습니다.

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

저는 당신이 사용할 필요가 없다고 생각합니다, 당신은 루프에 대한 표준을 사용할 수 있습니다.

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

이런 식으로 당신은 다음과 같은 루프 기능에 대한 표준을 가질 수 있습니다.break그리고.continue기본적으로 작동합니다.

또한, 그debugging will be easier

children은 그 자체로 루프입니다.

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

요소 속성에 대해 .attr('value')과 함께 작동합니다.

$("#element div").each(function() {
   $(this).attr('value')
});

언급URL : https://stackoverflow.com/questions/3024391/how-do-i-iterate-through-children-elements-of-a-div-using-jquery

반응형