【发布时间】:2011-03-02 18:00:02
【问题描述】:
我有一个 div,其中有几个输入元素...我想遍历每个元素。想法?
【问题讨论】:
我有一个 div,其中有几个输入元素...我想遍历每个元素。想法?
【问题讨论】:
使用children() 和each(),您可以选择将选择器传递给children
$('#mydiv').children('input').each(function () {
alert(this.value); // "this" is the current element in the loop
});
您也可以只使用直接子选择器:
$('#mydiv > input').each(function () { /* ... */ });
【讨论】:
each() 的回调函数。检查文档,链接在上面的答案中。
也可以遍历特定上下文中的所有元素,无论它们嵌套多深:
$('input', $('#mydiv')).each(function () {
console.log($(this)); //log every element found to console output
});
传递给 jQuery 'input' 选择器的第二个参数 $('#mydiv') 是上下文。在这种情况下,each() 子句将遍历 #mydiv 容器中的所有输入元素,即使它们不是 #mydiv 的直接子元素。
【讨论】:
$('input,select', $('#mydiv'))
如果需要循环遍历子元素递归:
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"));
注意: 在此示例中,我展示了使用对象注册的事件处理程序。
【讨论】:
$('#myDiv').children().each( (index, element) => {
console.log(index); // children's index
console.log(element); // children's element
});
这会遍历所有子元素,并且可以分别使用 element 和 index 分别访问它们具有索引值的元素。
【讨论】:
也可以这样做:
$('input', '#div').each(function () {
console.log($(this)); //log every element found to console output
});
【讨论】:
我认为你不需要使用each(),你可以使用标准for循环
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");
}
这样你就可以让break和continue等标准for循环功能默认工作
另外,debugging will be easier
【讨论】:
$.each() 总是比 for 循环慢,这是唯一使用它的答案。这里的关键是使用.eq() 来访问children 数组中的实际元素,而不是使用括号([])表示法。
children() 本身就是一个循环。
$('.element').children().animate({
'opacity':'0'
});
【讨论】:
它与 .attr('value') 一起工作,用于元素属性
$("#element div").each(function() {
$(this).attr('value')
});
【讨论】: