如果我有一个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?
如果你想要一个函数式的样式,像这样:
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
});
更好的解决方案:使用Javascript的原生array .from()并将HTMLCollection对象转换为数组,之后您可以使用标准的数组函数。
var t = document.getElementById('mytab1');
if(t) {
Array.from(t.rows).forEach((tr, row_ind) => {
Array.from(tr.cells).forEach((cell, col_ind) => {
console.log('Value at row/col [' + row_ind + ',' + col_ind + '] = ' + cell.textContent);
});
});
}
你也可以引用tr.rowIndex和cell。而不是使用row_ind和col_ind。
我更喜欢这种方法,而不是前2个投票最多的答案,因为它不会让你的代码与全局变量I, j, row和col混淆,因此它提供了干净的,模块化的代码,不会有任何副作用(或提高lint /编译器警告)…没有其他库(例如jquery)。此外,它使您的代码可以访问元素和索引变量,而不仅仅是元素,如果您喜欢隐藏索引,您可以在回调参数列表中忽略它。
如果你需要在旧版本(es2015之前)的Javascript中运行,Array.from可以被填充。