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)
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的直接子元素.
$('#myDiv').children().each( (index, element) => {
console.log(index); // children's index
console.log(element); // children's element
});
Run Code Online (Sandbox Code Playgroud)
这将遍历所有子元素,并且可以分别使用element和index分别访问具有索引值的元素。
如果您需要递归遍历子元素:
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)
注意: 在此示例中,我显示了向对象注册的事件处理程序。
也可以这样做:
$('input', '#div').each(function () {
console.log($(this)); //log every element found to console output
});
Run Code Online (Sandbox Code Playgroud)