我有一个div,它有几个输入元素在它…我想要遍历每一个元素。想法吗?
使用children()和each(),您可以选择将选择器传递给子代
$('#mydiv').children('input').each(function () {
alert(this.value); // "this" is the current element in the loop
});
你也可以只使用直接子选择器:
$('#mydiv > input').each(function () { /* ... */ });
也可以遍历特定上下文中的所有元素,无论它们嵌套有多深:
$('input', $('#mydiv')).each(function () {
console.log($(this)); //log every element found to console output
});
第二个参数$('#mydiv')传递给jQuery 'input'选择器是上下文。在这种情况下,each()子句将遍历#mydiv容器中的所有输入元素,即使它们不是#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"));
注意: 在本例中,我将展示向对象注册的事件处理程序。
也可以这样做:
$('input', '#div').each(function () {
console.log($(this)); //log every element found to console output
});
我认为你不需要使用each(),你可以使用standard 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
此外,调试也会更容易
$('#myDiv').children().each( (index, element) => {
console.log(index); // children's index
console.log(element); // children's element
});
这个迭代遍历所有的子元素,它们的带有index值的元素可以分别使用element和index访问。
它使用.attr('value')来处理元素属性
$("#element div").each(function() {
$(this).attr('value')
});
推荐文章
- 可以在setInterval()内部调用clearInterval()吗?
- 无法读取未定义的属性“msie”- jQuery工具
- jQuery:执行同步AJAX请求
- jQuery表格排序
- 如何禁用文本选择使用jQuery?
- 如何停止事件冒泡复选框点击
- Bootstrap抛出Uncaught错误:Bootstrap的JavaScript需要jQuery
- 如何删除和清除所有的本地存储数据
- 如何修改标签文本?
- 如何获得十六进制颜色值而不是RGB值?
- 如何将一个标题转换为jQuery的URL段塞?
- $(window).width()与媒体查询不一样
- AJAX请求中的内容类型和数据类型是什么?
- 如何打破_。在underscore.js中的每个函数
- 如何在jQuery中获得当前日期?