一尘不染

如何遍历JavaScript中的表行和单元格?

javascript

如果我有HTML表格…

<div id="myTabDiv">
<table name="mytab" id="mytab1">
  <tr> 
    <td>col1 Val1</td>
    <td>col2 Val2</td>
  </tr>
  <tr>
    <td>col1 Val3</td>
    <td>col2 Val4</td>
  </tr>
</table>
</div>

我将如何遍历所有表行(假设每次检查时行数都可能改变)并从JavaScript内的每一行中的每个单元格中检索值?


阅读 225

收藏
2020-04-25

共1个答案

一尘不染

如果您想遍历每一行(<tr>),知道/识别该行(<tr>),并遍历每一行(<td>)的每一列(<tr>),那么这就是要走的路。

var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
   //iterate through rows
   //rows would be accessed using the "row" variable assigned in the for loop
   for (var j = 0, col; col = row.cells[j]; j++) {
     //iterate through columns
     //columns would be accessed using the "col" variable assigned in the for loop
   }  
}

如果您只是想遍历cell(<td>),而忽略了您所在的行,那么这就是要走的路。

var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i++) {
     //iterate through cells
     //cells would be accessed using the "cell" variable assigned in the for loop
}
2020-04-25