如何使用 jQuery 迭代 div 的子元素?
我有一个 div,里面有几个输入元素...我想迭代每个元素。有想法吗?
I have a div and it has several input elements in it... I'd like to iterate through each of those elements. Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
使用
children()
和each()
,您可以选择将选择器传递给children
您也可以只使用直接子选择器:
Use
children()
andeach()
, you can optionally pass a selector tochildren
You could also just use the immediate child selector:
还可以迭代特定上下文中的所有元素,无论它们嵌套的深度如何:
传递给 jQuery 'input' 选择器的第二个参数 $('#mydiv') 是上下文。在这种情况下,each() 子句将迭代 #mydiv 容器内的所有输入元素,即使它们不是 #mydiv 的直接子元素。
It is also possible to iterate through all elements within a specific context, no mattter how deeply nested they are:
The second parameter $('#mydiv') which is passed to the jQuery 'input' Selector is the context. In this case the each() clause will iterate through all input elements within the #mydiv container, even if they are not direct children of #mydiv.
如果您需要递归地循环子元素:
If you need to loop through child elements recursively:
这将遍历所有子元素,并且可以分别使用 element 和 index 分别访问具有索引值的子元素。
This iterates through all the children and their element with index value can be accessed separately using element and index respectively.
也可以这样完成:
It can be done this way as well:
我认为您不需要使用
each()
,您可以使用标准的 for 循环,这样您就可以拥有标准的 for 循环功能,例如
break
和continue
默认情况下也可以工作,
调试会更容易
I don't think that you need to use
each()
, you can use standard for loopthis way you can have the standard for loop features like
break
andcontinue
works by defaultalso, the
debugging will be easier
Children() 本身就是一个循环。
children() is a loop in itself.
它与 .attr('value') 一起使用,用于元素属性
It's working with .attr('value'), for elements attributes