如何使用jQuery遍历div的子元素?

问题描述 投票:254回答:7

我有一个div,其中有几个输入元素...我想遍历每个元素。想法?

jquery iteration
7个回答
471
投票

使用children()children(),您可以选择将选择器传递给each()

each()

您也可以只使用直接子选择器:

children

54
投票

也可以遍历特定上下文中的所有元素,而不管它们嵌套的深度如何:

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

传递给jQuery'输入'选择器的第二个参数$('#mydiv')是上下文。在这种情况下,each()子句将遍历#mydiv容器中的所有输入元素,即使它们不是#mydiv的直接子代也是如此。


7
投票

如果您需要遍历子元素递归

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

注意:在此示例中,我显示了向对象注册的事件处理程序。


5
投票

也可以那样做。$('input', $('#mydiv')).each(function () { console.log($(this)); //log every element found to console output });


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

这将遍历所有子项,并且可以分别使用elementindex分别访问具有索引值的元素。


1
投票

children()本身就是一个循环。

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

1
投票

我认为您不需要使用$('#myDiv').children().each( (index, element) => { console.log(index); // children's index console.log(element); // children's element }); ,可以将标准用于循环

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

这样,您就可以拥有each()each()这样的循环功能的标准默认设置

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

© www.soinside.com 2019 - 2024. All rights reserved.