计算表格行中的列数

Muh*_*riq 35 javascript html-table

我有一张类似于的表:

<table id="table1">
<tr>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
</tr>
<tr>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
</tr>
<table>
Run Code Online (Sandbox Code Playgroud)

我想连续计算td元素的数量.我在尝试:

document.getElementById('').cells.length;
document.getElementById('').length;
document.getElementById('').getElementsByTagName('td').length;
Run Code Online (Sandbox Code Playgroud)

它没有显示实际结果.

Mar*_*sen 60

document.getElementById('table1').rows[0].cells.length
Run Code Online (Sandbox Code Playgroud)

cell不是表的属性,行是.但是,单元格是一行的属性

  • 这仅适用于简单情况,其中所有单元格的colspan = 1,并且所有行具有相同的列数.(HTML允许行具有不同数量的列,在这种情况下,列太少的行会在末尾获得空白.) (3认同)
  • 不明白你的意思.问题是关于连续的细胞.如果colspan = 2且缺少两个仍然意味着只有一个单元格.使用rowspan时会有点混乱,但它仍然是正确的,请看这个小提琴:http://jsfiddle.net/GF6Dr/如果你想要一个表中有多少个单元格,那么就做所有单元格的最大值. (2认同)

Nic*_*tti 5

你可以做

alert(document.getElementById('table1').rows[0].cells.length)
Run Code Online (Sandbox Code Playgroud)

在这里小提琴http://jsfiddle.net/TEZ73/


Emi*_*gas 5

为什么不使用reduce以便我们可以考虑colspan呢?:)

function getColumns(table) {
    var cellsArray = [];
    var cells = table.rows[0].cells;

    // Cast the cells to an array
    // (there are *cooler* ways of doing this, but this is the fastest by far)
    // Taken from /sf/answers/1060098861/
    for(var i=-1, l=cells.length; ++i!==l; cellsArray[i]=cells[i]);

    return cellsArray.reduce(
        (cols, cell) =>
            // Check if the cell is visible and add it / ignore it
            (cell.offsetParent !== null) ? cols += cell.colSpan : cols,
        0
    );
}
Run Code Online (Sandbox Code Playgroud)