Javascript:查找所有“输入”在表中
有没有更短的方法在 JavaScript 中编写这个?
var data = [];
var table = document.getElementById( 'address' );
var rows = table.getElementsByTagName( 'tr' );
for ( var x = 0; x < rows.length; x++ ) {
var td = rows[x].getElementsByTagName( 'td' );
for ( var y = 0; y < td.length; y++ ) {
var input = td[y].getElementsByTagName( 'input' );
for ( var z = 0; z < input.length; z++ ) {
data.push( input[z].id );
}
}
}
Is there a shorter way to write this in JavaScript?
var data = [];
var table = document.getElementById( 'address' );
var rows = table.getElementsByTagName( 'tr' );
for ( var x = 0; x < rows.length; x++ ) {
var td = rows[x].getElementsByTagName( 'td' );
for ( var y = 0; y < td.length; y++ ) {
var input = td[y].getElementsByTagName( 'input' );
for ( var z = 0; z < input.length; z++ ) {
data.push( input[z].id );
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
element.getElementsByTagName
< /a> 查找所有后代,而不仅仅是子代,因此:element.getElementsByTagName
finds all descendants, not only children, so:是的。
请注意,即使在具有三个循环的较长版本中,您也可以说:
Yep.
Note, even in your longer version with three loops you can also say:
对于现代浏览器
:)
现场演示: http://jsfiddle. net/HHaGg/
因此,我使用了
map
方法,而不是for
循环 - 每个数组元素(每个 INPUT 节点)都替换为其 ID价值。另请注意,`inputs.map(... 不起作用,因为
inputs
是一个 NodeList 元素 - 它是一个类似数组的对象,但不是标准数组。要仍然使用map
方法,我们只需将其转换为一个数组,这就是[].slice.call(inputs )
对我们来说。For modern browsers
:)
Live demo: http://jsfiddle.net/HHaGg/
So instead of a
for
loop, I make use of themap
method - each array element (each INPUT node) is replaced with its ID value.Also note that
`inputs.map(...
doesn't work sinceinputs
is a NodeList element - it's an array-like object, but not an standard array. To still use themap
method on it, we just have to transform it into an array which is what[].slice.call( inputs )
does for us.