// 构造表格的 HTML 字符串
let tableHtml = `
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
`;
// 构造表格的数据
const data = [
{ name: '张三', age: 20, gender: '男' },
{ name: '李四', age: 25, gender: '女' },
{ name: '王五', age: 30, gender: '男' },
];
// 构造表格的 tbody 的 HTML 字符串
let tbodyHtml = '<tbody>';
data.forEach(item => {
tbodyHtml += `
<tr>
<td>${item.name}</td>
<td>${item.age}</td>
<td>${item.gender}</td>
</tr>
`;
});
tbodyHtml += '</tbody>';
// 将 tbody 的 HTML 字符串添加到表格的 HTML 字符串中
tableHtml += tbodyHtml;
tableHtml += '</table>';
// 将表格的 HTML 字符串添加到页面中
document.body.insertAdjacentHTML('beforeend'
使用字符串拼接的方式动态构造 HTML 表格
最新推荐文章于 2024-05-20 15:31:49 发布