如果我有一个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
如果你想要一个函数式的样式,像这样:
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
});