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

如何在JS端调用指定表格元素并添加含数据的新行?

如何用JavaScript调用表格并添加数据行

首先要获取到目标表格元素,因为表格带有table类名,直接用document.querySelector就能定位:

const table = document.querySelector('.table');

接下来创建包含数据的新行,步骤如下:

  1. 创建表格行元素:
const newRow = document.createElement('tr');
  1. 为每个表头对应的单元格创建元素并填充数据,比如我们要添加一行数据:5(Lot数量)、100(单Lot价格)、500(总金额):
// 创建第一个单元格(对应Number of Lots)
const numCell = document.createElement('td');
numCell.textContent = '5';

// 创建第二个单元格(对应Price of a Lot)
const priceCell = document.createElement('td');
priceCell.textContent = '100';

// 创建第三个单元格(对应Total Amount of Lots)
const totalCell = document.createElement('td');
totalCell.textContent = '500';
  1. 把三个单元格依次添加到新行里:
newRow.appendChild(numCell);
newRow.appendChild(priceCell);
newRow.appendChild(totalCell);
  1. 最后把新行添加到表格中。如果表格里没有<tbody>,浏览器会自动为表格生成一个,你可以直接把行添加到表格,或者明确找到tbody添加(更规范):
// 方式1:直接添加到表格
table.appendChild(newRow);

// 方式2:找到tbody添加(推荐,符合HTML表格结构规范)
const tbody = table.querySelector('tbody') || table.appendChild(document.createElement('tbody'));
tbody.appendChild(newRow);

如果想批量添加多行,或者用更简洁的写法,也可以用innerHTML(注意如果数据是用户输入的,要防范XSS风险):

const table = document.querySelector('.table');
const tbody = table.querySelector('tbody') || table.appendChild(document.createElement('tbody'));
// 插入一行数据
tbody.innerHTML += `
  <tr>
    <td>3</td>
    <td>150</td>
    <td>450</td>
  </tr>
`;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:44:59