如果我有一个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?


当前回答

这里有一个使用现代Javascript ES6+的解决方案

    const rows = document.querySelector("table")?.rows;
    if (!rows) {
      return;
    }
    Array.from(rows).forEach(row => {
      console.log(row);
      const cells = Array.from(row.cells);
      cells.forEach(cell => {
        console.log(cell);
      });
    });

Array.from()将HTMLCollection的行和/或单元格转换为一个常规的Javascript数组,你可以迭代通过。

表的文档。行使用率:https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/rows

行的文档。cell用法:https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement

其他回答

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

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

如果您只想遍历单元格(<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
}

这里有一个使用现代Javascript ES6+的解决方案

    const rows = document.querySelector("table")?.rows;
    if (!rows) {
      return;
    }
    Array.from(rows).forEach(row => {
      console.log(row);
      const cells = Array.from(row.cells);
      cells.forEach(cell => {
        console.log(cell);
      });
    });

Array.from()将HTMLCollection的行和/或单元格转换为一个常规的Javascript数组,你可以迭代通过。

表的文档。行使用率:https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/rows

行的文档。cell用法:https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement

我的解决方案,使用es6:

var table = document.getElementById('mytab1');

var data = [...table.rows].map(row => [...row.cells].map(td => td.innerText));

console.log(data)

引用: https://developer.mozilla.org/pt-BR/docs/Web/API/HTMLCollection

您可以考虑使用jQuery。使用jQuery,这是超级简单的,可能看起来像这样:

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

var表= . getelementbyid(“mytab1”); var r = 0;//开始计算表中的行数 而(行= table.rows (r + +)) { var c = 0;//开始计数行中的列 而(细胞= row.cells (c++)) { cell.innerHTML = ' [R ' + R + ' C ' + C + '] ';//用cell做某事 } } <表id = " mytab1 " > < tr > A1 < td > < / td > < td > A2 < / td > < td > A3 td > < / < / tr > < tr > < td > B1 < / td > < td > B2 < / td > < td > B3 td > < / < / tr > < tr > < td > C1 < / td > < td > C2 < / td > < td > C3 td > < / < / tr > 表> < /

每次遍历while循环时,r/c迭代器都会增加,集合中的新行/单元格对象会被赋值给行/单元格变量。当集合中没有更多的行/单元格时,将false赋给行/单元格变量,并通过while循环停止(退出)进行迭代。