Javascript:在表中查找所有“输入”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7371805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:00:04  来源:igfitidea点击:

Javascript: find all "input" in a table

javascripthtmldom

提问by sid_com

Is there a shorter way to write this in 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 );
            }
        }
    }

采纳答案by Jon

element.getElementsByTagNamefinds all descendants, not only children, so:

element.getElementsByTagName找到所有后代,而不仅仅是孩子,所以:

<script type="text/javascript> 

    var data = []; 
    var table = document.getElementById( 'address' ); 
    var input = table.getElementsByTagName( 'input' ); 
    for ( var z = 0; z < input.length; z++ ) { 
        data.push( input[z].id ); 
    } 

</script> 

回答by nnnnnn

Yep.

是的。

var data = [],
    inputs = document.getElementById('address').getElementsByTagName('input');

for (var z=0; z < inputs.length; z++)
  data.push(inputs[z].id);

Note, even in your longer version with three loops you can also say:

请注意,即使在具有三个循环的较长版本中,您也可以说:

var rows = table.rows;
// instead of
var rows = table.getElementsByTagName('tr');

// and, noting that it returns <th> cells as well as <td> cells,
// which in many cases doesn't matter:
var tds = rows[x].cells;
// instead of
var tds = rows[x].getElementsByTagName('td');

回答by ?ime Vidas

For modern browsers :)

对于现代浏览器 :)

var table, inputs, arr;

table = document.getElementById( 'test' );
inputs = table.querySelectorAll( 'input' );
arr = [].slice.call( inputs ).map(function ( node ) { return node.id; });

Live demo:http://jsfiddle.net/HHaGg/

现场演示:http : //jsfiddle.net/HHaGg/

So instead of a forloop, I make use of the mapmethod - each array element (each INPUT node) is replaced with its ID value.

因此for,我使用了该map方法而不是循环- 每个数组元素(每个 INPUT 节点)都替换为其 ID 值。

Also note that `inputs.map(...doesn't work since inputsis a NodeListelement - it's an array-like object, but not an standard array. To still use the mapmethod on it, we just have to transform it into an array which is what [].slice.call( inputs )does for us.

另请注意,`inputs.map(...它不起作用,因为它inputs是一个NodeList元素 - 它是一个类似数组的对象,但不是标准数组。要仍然map在其上使用该方法,我们只需要将其转换为一个数组,这[].slice.call( inputs )对我们有用。