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

如何不使用jQuery,用原生JavaScript动态更新HTML表格内容?

原生JavaScript实现表格行的更新(按Name查找)

高效方案:利用data属性标识行

在添加行时给每行绑定data-name属性存储Name值,后续可直接通过该属性快速定位目标行,避免遍历所有行,效率更高。

修改后的添加行函数

function addRow(name, age) {
  const table = document.getElementById("data-table");
  // 先检查是否已存在同名行,避免重复添加(可选)
  const existingRow = table.querySelector(`tr[data-name="${name}"]`);
  if (existingRow) {
    updateRow(name, age);
    return;
  }
  
  const row = table.insertRow(-1);
  // 添加data-name属性用于快速查找
  row.dataset.name = name;
  const cell1 = row.insertCell(0);
  const cell2 = row.insertCell(1);
  cell1.textContent = name; // 纯文本场景用textContent更安全,避免XSS风险
  cell2.textContent = age;
}

实现更新行函数

function updateRow(name, newAge) {
  const table = document.getElementById("data-table");
  // 通过data属性直接定位目标行
  const targetRow = table.querySelector(`tr[data-name="${name}"]`);
  if (!targetRow) {
    console.log(`未找到Name为${name}的行`);
    return;
  }
  // 更新第二列(Age)的内容
  targetRow.cells[1].textContent = newAge;
}

兼容方案:遍历行查找(无需修改原有添加逻辑)

如果不想改动已有的添加行代码,可以通过遍历表格行、匹配Name单元格值来定位目标行:

function updateRow(name, newAge) {
  const table = document.getElementById("data-table");
  // 获取所有数据行,跳过表头(从索引1开始)
  const rows = table.querySelectorAll("tr:not(:first-child)");
  
  for (const row of rows) {
    const rowName = row.cells[0].textContent.trim();
    if (rowName === name) {
      row.cells[1].textContent = newAge;
      return; // 找到目标行后立即退出循环,提升效率
    }
  }
  
  console.log(`未找到Name为${name}的行`);
}

注意事项

  • 优先使用textContent:纯文本场景下,textContent比innerHTML更安全,能避免潜在的XSS攻击,性能也更优。
  • 重复行处理:在addRow中加入重复检查,可自动判断是添加新行还是更新现有行,优化用户体验。
  • 性能差异:基于data属性的查找方式时间复杂度为O(1),遍历行的方式为O(n),数据量较大时优先选择前者。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 17:50:22