如何使用jQuery迭代div的子元素?

Sha*_*oon 242 iteration jquery

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

And*_*y E 450

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

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

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

$('#mydiv > input').each(function () { /* ... */ });
Run Code Online (Sandbox Code Playgroud)

  • 然后在闭包中使用$(this)来访问循环中的"当前"项. (64认同)

Liq*_*aut 54

也可以迭代特定上下文中的所有元素,没有matter它们是如何深度嵌套的:

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

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


Sur*_*off 9

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

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


tom*_*rod 6

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

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"));   
Run Code Online (Sandbox Code Playgroud)

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


Uma*_*har 6

也可以这样做:

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