如何在JavaScript中迭代表格行和单元格?

2022-08-30 00:56:03

如果我有一个 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中检索每行中每个单元格的值?


答案 1

如果你想遍历每一行(),知道/识别row(),并循环访问每行()的每个列(),那么这就是要走的路。<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
}

答案 2

你可以考虑使用jQuery。使用jQuery,它非常容易,可能看起来像这样:

$('#mytab1 tr').each(function(){
    $(this).find('td').each(function(){
        //do your stuff, you can use $(this) to get current cell
    })
})