js实现table
JavaScript 实现动态表格
使用 JavaScript 动态创建和操作表格可以通过 DOM 操作实现。以下是几种常见场景的实现方法。
创建基础表格结构
通过 document.createElement 构建表格元素并插入到页面中:
// 创建 table 元素
const table = document.createElement('table');
table.border = '1';
// 创建表头
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
['姓名', '年龄', '城市'].forEach(text => {
const th = document.createElement('th');
th.textContent = text;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
// 创建表格内容
const tbody = document.createElement('tbody');
const data = [
['张三', 25, '北京'],
['李四', 30, '上海']
];
data.forEach(rowData => {
const tr = document.createElement('tr');
rowData.forEach(cellData => {
const td = document.createElement('td');
td.textContent = cellData;
tr.appendChild(td);
});
tbody.appendChild(tr);
});
// 组装表格
table.appendChild(thead);
table.appendChild(tbody);
document.body.appendChild(table);
动态添加行
为已有表格追加新行数据:
function addTableRow(tableId, rowData) {
const tbody = document.querySelector(`#${tableId} tbody`);
const tr = document.createElement('tr');
rowData.forEach(cellData => {
const td = document.createElement('td');
td.textContent = cellData;
tr.appendChild(td);
});
tbody.appendChild(tr);
}
// 使用示例
addTableRow('myTable', ['王五', 28, '广州']);
响应式表格排序
实现点击表头排序功能:
function setupTableSort(tableId) {
const table = document.getElementById(tableId);
const headers = table.querySelectorAll('th');
headers.forEach((header, index) => {
header.style.cursor = 'pointer';
header.addEventListener('click', () => {
const tbody = table.querySelector('tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
rows.sort((a, b) => {
const aText = a.cells[index].textContent;
const bText = b.cells[index].textContent;
return isNaN(aText) ? aText.localeCompare(bText) : aText - bText;
});
// 清空并重新插入排序后的行
tbody.innerHTML = '';
rows.forEach(row => tbody.appendChild(row));
});
});
}
使用模板字符串生成
对于简单表格可以使用模板字符串快速生成:
const data = [
{ name: '张三', age: 25, city: '北京' },
{ name: '李四', age: 30, city: '上海' }
];
function generateTable(data) {
return `
<table border="1">
<thead>
<tr>
${Object.keys(data[0]).map(key => `<th>${key}</th>`).join('')}
</tr>
</thead>
<tbody>
${data.map(row => `
<tr>
${Object.values(row).map(val => `<td>${val}</td>`).join('')}
</tr>
`).join('')}
</tbody>
</table>
`;
}
document.body.innerHTML = generateTable(data);
使用现代框架示例(React)
在 React 中创建表格组件:

function DataTable({ data }) {
return (
<table>
<thead>
<tr>
{Object.keys(data[0]).map(key => (
<th key={key}>{key}</th>
))}
</tr>
</thead>
<tbody>
{data.map((row, i) => (
<tr key={i}>
{Object.values(row).map((val, j) => (
<td key={j}>{val}</td>
))}
</tr>
))}
</tbody>
</table>
);
}
注意事项
- 动态创建的表格需要合理设置
border、cellpadding等属性保证显示效果 - 大数据量表格建议使用虚拟滚动技术优化性能
- 考虑添加斑马纹样式(交替行颜色)提升可读性
- 复杂的交互功能(如编辑、筛选)建议使用现成的表格库如 DataTables、ag-Grid 等






