2010-06-11 64 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 });