我有一个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')
});
推荐文章
- 如何使用jQuery检测页面的滚动位置
- 如何在JSON中使用杰克逊更改字段名
- 在JavaScript中根据键值查找和删除数组中的对象
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- jQuery: keyPress退格键不火?
- XMLHttpRequest Origin null不允许Access-Control-Allow-Origin for file:/// to file:///(无服务器)
- 重置setTimeout
- jQuery有不聚焦的方法吗?
- jQuery -替换字符串中某个字符的所有实例
- Ng-repeat结束事件
- 模糊vs聚焦-有什么真正的区别吗?
- 如何用jQuery / JavaScript解析JSON数据?
- jQuery在请求体中发布有效的json
- jQuery中的live()转换为on()
- jQuery等价于JavaScript的addEventListener方法