js实现table
使用原生JavaScript创建表格
创建HTML表格需要结合DOM操作,以下是基础实现方法:
<!DOCTYPE html>
<html>
<body>
<div id="tableContainer"></div>
<script>
// 创建表格元素
const table = document.createElement('table');
table.border = '1';
// 创建表头
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
['姓名', '年龄', '城市'].forEach(headerText => {
const th = document.createElement('th');
th.textContent = headerText;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// 创建表格内容
const tbody = document.createElement('tbody');
const data = [
['张三', 25, '北京'],
['李四', 30, '上海'],
['王五', 28, '广州']
];
data.forEach(rowData => {
const row = document.createElement('tr');
rowData.forEach(cellData => {
const td = document.createElement('td');
td.textContent = cellData;
row.appendChild(td);
});
tbody.appendChild(row);
});
table.appendChild(tbody);
// 将表格添加到页面
document.getElementById('tableContainer').appendChild(table);
</script>
</body>
</html>
动态生成表格数据
对于动态数据,可以封装成函数:

function generateTable(data, headers) {
const table = document.createElement('table');
table.className = 'data-table';
// 添加表头
if (headers && headers.length) {
const thead = table.createTHead();
const headerRow = thead.insertRow();
headers.forEach(header => {
const th = document.createElement('th');
th.textContent = header;
headerRow.appendChild(th);
});
}
// 添加数据行
const tbody = table.createTBody();
data.forEach(rowData => {
const row = tbody.insertRow();
Object.values(rowData).forEach(value => {
const cell = row.insertCell();
cell.textContent = value;
});
});
return table;
}
// 使用示例
const employeeData = [
{ id: 1, name: '张三', department: '研发' },
{ id: 2, name: '李四', department: '市场' }
];
const table = generateTable(employeeData, ['ID', '姓名', '部门']);
document.body.appendChild(table);
添加表格交互功能
实现排序和筛选功能:

// 为表格添加排序功能
function addSorting(table) {
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 aText.localeCompare(bText, undefined, { numeric: true });
});
// 移除现有行
rows.forEach(row => tbody.removeChild(row));
// 添加排序后的行
rows.forEach(row => tbody.appendChild(row));
});
});
}
// 调用排序功能
const table = generateTable(employeeData, ['ID', '姓名', '部门']);
addSorting(table);
使用模板字符串生成表格
对于简单表格,可以使用模板字符串:
function createTableFromTemplate(data) {
const tableHTML = `
<table class="template-table">
<thead>
<tr>
${Object.keys(data[0]).map(key => `<th>${key}</th>`).join('')}
</tr>
</thead>
<tbody>
${data.map(row => `
<tr>
${Object.values(row).map(value => `<td>${value}</td>`).join('')}
</tr>
`).join('')}
</tbody>
</table>
`;
const container = document.createElement('div');
container.innerHTML = tableHTML;
return container.firstChild;
}
表格样式优化
添加基础CSS样式:
.data-table {
width: 100%;
border-collapse: collapse;
margin: 1rem 0;
}
.data-table th, .data-table td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
.data-table th {
background-color: #f2f2f2;
position: sticky;
top: 0;
}
.data-table tr:nth-child(even) {
background-color: #f9f9f9;
}
.data-table tr:hover {
background-color: #f1f1f1;
}
这些方法涵盖了从基础到进阶的JavaScript表格实现,可以根据实际需求选择适合的方案或组合使用。






