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


当前回答

如果你想遍历每一行(<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
}

其他回答

如果你想要一个函数式的样式,像这样:

    const table = document.getElementById("mytab1");
    const cells = table.rows.toArray()
                  .flatMap(row => row.cells.toArray())
                  .map(cell => cell.innerHTML); //["col1 Val1", "col2 Val2", "col1 Val3", "col2 Val4"]

你可以修改HTMLCollection的原型对象(允许以类似于c#中的扩展方法的方式使用),并嵌入一个将集合转换为数组的函数,允许使用具有上述风格的高阶函数(类似于c#中的linq风格):

    Object.defineProperty(HTMLCollection.prototype, "toArray", {
        value: function toArray() {
            return Array.prototype.slice.call(this, 0);
        },
        writable: true,
        configurable: true
    });

使用一个for循环:

var table = document.getElementById('tableID');  
var count = table.rows.length;  
for(var i=0; i<count; i++) {    
    console.log(table.rows[i]);    
}

我的解决方案,使用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

您可以使用. queryselectorall()来选择所有td元素,然后使用. foreach()循环这些元素。它们的值可以用.innerHTML检索:

管理细胞=文档。 细胞. forEach(功能(细胞){ 控制台日志(细胞。innerHTML); }) <table . the 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 >

如果你只想从一个特定的行中选择列,你可以使用伪类:n -child()来选择一个特定的tr,可选地结合子组合子(>)(如果你有一个表中表):

const细胞=文档。 细胞. forEach(功能(细胞){ 控制台日志(细胞。innerHTML); }) <table . the 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 >

这是一个使用childNodes和HTMLCollection的不同方法

    <script>
        var tab = document.getElementsByTagName("table")
        for (var val of tab[0].childNodes[1].childNodes.values())
            if (HTMLCollection.prototype.isPrototypeOf(val.children)) {
                for (var i of val.children) {
                    console.log(i.childNodes[0])
                }
            }
    </script>