我有一个div,它有几个输入元素在它…我想要遍历每一个元素。想法吗?
当前回答
我认为你不需要使用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
此外,调试也会更容易
其他回答
也可以遍历特定上下文中的所有元素,无论它们嵌套有多深:
$('input', $('#mydiv')).each(function () {
console.log($(this)); //log every element found to console output
});
第二个参数$('#mydiv')传递给jQuery 'input'选择器是上下文。在这种情况下,each()子句将遍历#mydiv容器中的所有输入元素,即使它们不是#mydiv的直接子元素。
使用children()和each(),您可以选择将选择器传递给子代
$('#mydiv').children('input').each(function () {
alert(this.value); // "this" is the current element in the loop
});
你也可以只使用直接子选择器:
$('#mydiv > input').each(function () { /* ... */ });
我认为你不需要使用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
此外,调试也会更容易
如果你需要递归地遍历子元素:
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"));
注意: 在本例中,我将展示向对象注册的事件处理程序。
它使用.attr('value')来处理元素属性
$("#element div").each(function() {
$(this).attr('value')
});
推荐文章
- 在数组中获取所有选中的复选框
- JSHint和jQuery: '$'没有定义
- 用jQuery检查Internet连接是否存在?
- 如何使用滑动(或显示)函数在一个表行?
- 如何用JavaScript截屏一个div ?
- 如何检测“搜索”HTML5输入的清除?
- 当元素从DOM中移除时触发事件
- Ajax成功事件不工作
- 引导下拉与Hover
- jQuery的.bind() vs. on()
- jQuery .live() vs .on()方法,用于在加载动态html后添加单击事件
- 事件。returnValue已弃用。请使用标准的event.preventDefault()
- 如何处理模式关闭事件在Twitter引导?
- 防止浏览器加载拖放文件
- 清除输入文本内的图标