在JavaScript中给<table>
元素添加<tr>
(表格行)通常涉及到DOM操作。以下是基础概念及相关操作:
<table>
元素:HTML中用于创建表格的标签。<tr>
元素:定义表格中的一行。<tr>
元素。<tr>
元素。假设我们有一个简单的HTML表格:
<table id="myTable" border="1">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<!-- 动态添加的行将出现在这里 -->
</tbody>
</table>
我们可以使用以下JavaScript代码来动态添加一行:
// 获取表格的tbody元素
var tableBody = document.querySelector("#myTable tbody");
// 创建一个新的<tr>元素
var newRow = document.createElement("tr");
// 创建并添加第一个单元格<td>
var cell1 = document.createElement("td");
cell1.textContent = "张三";
newRow.appendChild(cell1);
// 创建并添加第二个单元格<td>
var cell2 = document.createElement("td");
cell2.textContent = "25";
newRow.appendChild(cell2);
// 将新行添加到表格的tbody中
tableBody.appendChild(newRow);
或者,使用更简洁的方法:
var tableBody = document.querySelector("#myTable tbody");
var newRow = `<tr>
<td>李四</td>
<td>30</td>
</tr>`;
tableBody.innerHTML += newRow;
DocumentFragment
)来批量添加行,减少重绘和回流。var tableBody = document.querySelector("#myTable tbody");
var fragment = document.createDocumentFragment();
for (var i = 0; i < 10; i++) {
var newRow = document.createElement("tr");
var cell1 = document.createElement("td");
cell1.textContent = "用户" + i;
var cell2 = document.createElement("td");
cell2.textContent = i * 10;
newRow.appendChild(cell1);
newRow.appendChild(cell2);
fragment.appendChild(newRow);
}
tableBody.appendChild(fragment);
通过这种方式,可以显著提高大量数据添加时的性能。
领取专属 10元无门槛券
手把手带您无忧上云