2010-06-11 63 views

回答

370

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

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

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

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

然后在闭包中使用$(this)来访问循环中的“当前”项目。 – amarsuperstar 2010-06-11 16:15:44

+1

@amarsuperstar:刚刚在添加该信息的过程中:-) – 2010-06-11 16:17:13

+0

有没有办法知道“n”的值,假设$(this)是父节点的第n个孩子? – 2016-09-21 16:15:57

40

也可以通过所有元素进行迭代在特定的情况下,没有任何mattter嵌套得如此之深:

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

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

+1

可能是因为嵌套这个解决方案为我工作,而另一个没有。出于这个原因,我认为这通常是更好的解决方案。 – arame3333 2015-10-28 07:56:03

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