我有一个div,其中有几个输入元素...我想遍历每个元素。想法?
也可以遍历特定上下文中的所有元素,而不管它们嵌套的深度如何:
$('#mydiv').children('input').each(function () {
alert(this.value); // "this" is the current element in the loop
});
传递给jQuery'输入'选择器的第二个参数$('#mydiv')是上下文。在这种情况下,each()子句将遍历#mydiv容器中的所有输入元素,即使它们不是#mydiv的直接子代也是如此。
如果您需要遍历子元素递归:
$('#mydiv > input').each(function () { /* ... */ });
注意:在此示例中,我显示了向对象注册的事件处理程序。
也可以那样做。$('input', $('#mydiv')).each(function () {
console.log($(this)); //log every element found to console output
});
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"));
这将遍历所有子项,并且可以分别使用element和index分别访问具有索引值的元素。
children()本身就是一个循环。
$('input', '#div').each(function () {
console.log($(this)); //log every element found to console output
});
我认为您不需要使用$('#myDiv').children().each( (index, element) => {
console.log(index); // children's index
console.log(element); // children's element
});
,可以将标准用于循环
$('.element').children().animate({
'opacity':'0'
});
这样,您就可以拥有each()
和each()
这样的循环功能的标准默认设置
也,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");
}