Javascript 计算表格行中的列数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10043760/
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-23 23:37:01  来源:igfitidea点击:

Count number of columns in a table row

javascripthtml-table

提问by Muhammad Imran Tariq

I have a table similar to:

我有一张类似于:

<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>

I want to count the number of td element in a row. I am trying:

我想计算一行中 td 元素的数量。我在尝试:

document.getElementById('').cells.length;
document.getElementById('').length;
document.getElementById('').getElementsByTagName('td').length;

It did not show actual result.

它没有显示实际结果。

回答by Martin Hansen

document.getElementById('table1').rows[0].cells.length

cells is not a property of a table, rows are. Cells is a property of a row though

单元格不是表格的属性,行是。单元格虽然是一行的属性

回答by Nicola Peluchetti

You could do

你可以做

alert(document.getElementById('table1').rows[0].cells.length)

fiddle here http://jsfiddle.net/TEZ73/

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

回答by Emilio Venegas

Why not use reduce so that we can take colspan into account? :)

为什么不使用 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 https://stackoverflow.com/a/15144269/6424295
    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
    );
}

回答by NVRM

Count all tdin table1:

计算表 1 中的所有td

console.log(
table1.querySelectorAll("td").length
)
<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>

Count all td into each trof table1.

将所有 td 计入table1 的每个tr

table1.querySelectorAll("tr").forEach(function(e){
 console.log( e.querySelectorAll("td").length )
})
<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>

回答by Han Zhang

If the colspanor rowspanis all set to 1, counting the children tds will give the correct answer. However, if there are spans, we cannot count the number of columns exactly, even by the maximum number of tds of the rows. Consider the following example:

如果colspanrowspan全部设置为1,则数孩子tds 将给出正确答案。但是,如果有跨度,我们无法准确计算列数,即使是行的最大tds数。考虑以下示例:

var mytable = document.getElementById('table')
for (var i=0; i < mytable.rows.length; ++i) {
 document.write(mytable.rows[i].cells.length + "<br>");
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
  padding: 3px;
}
<table id="table">
    <thead>
        <tr>
            <th colspan="2">Header</th>
            <th rowspan="2">Hi</th>
        </tr>
        <tr>
            <th>Month</th>
            <th>Savings</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2">hello</td>
            <td>world</td>
        </tr>
        <tr>
            <td>hello</td>
            <td colspan="2">again</td>
        </tr>
    </tbody>
</table>

回答by hvgotcodes

First off, when you call getElementById, you need to provide an id. o_O

首先,当您调用 时getElementById,您需要提供一个 id。o_o

The only item in your dom with an id is the tableelement. If you can, you could add ids (make sure they are unique) to your trelements.

dom 中唯一带有 id 的项目是table元素。如果可以,您可以为tr元素添加 id(确保它们是唯一的)。

Alternatively, you can use getElementsByTagName('tr')to get a list of trelements in your document, and then get the number of tds.

或者,您可以使用getElementsByTagName('tr')获取tr文档中的元素列表,然后获取 tds 的数量。

here is a fiddle that console logs the results...

这是控制台记录结果的小提琴......

回答by Skeets

It's a bad idea to count the tdelements to get the number of columns in your table, because tdelements can span multiple columns with colspan.

计算td元素以获取表格中的列数是一个坏主意,因为td元素可以使用colspan.

Here's a simple solution using jquery:

这是一个使用 jquery 的简单解决方案:

var length = 0;
$("tr:first").find("td,th").each(function(){
 var colspan = $(this).attr("colspan");
  if(typeof colspan !== "undefined" && colspan > 0){
   length += parseInt(colspan);
  }else{
        length += 1;
  }
});

$("div").html("number of columns: "+length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
  <td>single</td>
  <td colspan="2">double</td>
  <td>single</td>
  <td>single</td>
</tr>
</table>
<div></div>

For a plain Javascript solution, see Emilio's answer.

有关普通的 Javascript 解决方案,请参阅 Emilio 的回答。

回答by Nam Le

<table id="table1">
<tr>
  <td colspan=4><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>
<script>
    var row=document.getElementById('table1').rows.length;
    for(i=0;i<row;i++){
    console.log('Row '+parseFloat(i+1)+' : '+document.getElementById('table1').rows[i].cells.length +' column');
    }
</script>

Result:

结果:

Row 1 : 1 column
Row 2 : 4 column

回答by user5448317

$('#table1').find(input).length