You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么用JS循环遍历HTML表格取值时每次迭代都得到相同结果?

问题描述

我有一个包含多个文本值的HTML表格,需要先提取所有单元格内容再转为数组,因此编写了遍历表格行列的循环逻辑,但尝试获取单元格内容时每次都返回相同的数值,代码示例如下:

HTML代码

<table id="my-table">
  <tr id="default-row">
    <td class = "cell" contenteditable="true">3</td>
    <td class = "cell" contenteditable="true">10</td>
    <td class = "cell" contenteditable="true">56</td>
    <td class = "cell" contenteditable="true">3</td>
  </tr>
  <tr>
    <td class = "cell" contenteditable="true">3</td>
    <td class = "cell" contenteditable="true">5</td>
    <td class = "cell" contenteditable="true">3</td>
    <td class = "cell" contenteditable="true">4</td>
  </tr>
  <tr>
    <td class = "cell" contenteditable="true">5</td>
    <td class = "cell" contenteditable="true">6</td>
    <td class = "cell" contenteditable="true">7</td>
    <td class = "cell" contenteditable="true">8</td>
  </tr>
  <tr>
    <td class = "cell" contenteditable="true">12</td>
    <td class = "cell" contenteditable="true">6</td>
    <td class = "cell" contenteditable="true">7</td>
    <td class = "cell" contenteditable="true">3</td>
  </tr>
</table>

原有JS代码

const cellValues = []

var table = document.getElementById("my-table");
//iterate trough rows
for(var i = 0, row; row = table.rows[i]; i++) {
  //iterate trough columns
  for(var j = 0, col; col = row.cells[j]; j++) {
    cellValues.push(document.querySelector(".cell").textContent)
    //get text value of the cell
  }
}
console.log(cellValues)
解决方案

问题原因

document.querySelector(".cell") 会默认匹配整个文档中第一个类名为cell的元素,循环内重复调用该方法只会一直返回第一个单元格的内容,和当前遍历到的单元格没有关联。
你在循环内已经通过row.cells[j]拿到了当前遍历的单元格对象col,直接读取该对象的textContent属性即可。

修正后代码(一维数组输出)

const cellValues = []
const table = document.getElementById("my-table");
// 遍历所有行
for(let i = 0, row; row = table.rows[i]; i++) {
  // 遍历当前行的所有列
  for(let j = 0, col; col = row.cells[j]; j++) {
    // trim()用于清除内容前后可能存在的多余空白字符
    cellValues.push(col.textContent.trim())
  }
}
console.log(cellValues)

可选方案:按行分组的二维数组输出

如果需要保留表格的行结构,可以使用以下代码:

const tableValues = []
const table = document.getElementById("my-table");
for(let i = 0, row; row = table.rows[i]; i++) {
  const rowValues = []
  for(let j = 0, col; col = row.cells[j]; j++) {
    rowValues.push(col.textContent.trim())
  }
  tableValues.push(rowValues)
}
console.log(tableValues)

内容的提问来源于stack exchange,提问作者Vitaliy Povestev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:36:00