js实现表格
使用原生JavaScript创建表格
创建表格的基本方法是使用document.createElement动态生成table元素及其子元素(thead、tbody、tr、td等)。以下是一个完整示例:
// 创建表格元素
const table = document.createElement('table');
table.setAttribute('border', '1');
// 创建表头
const thead = table.createTHead();
const headerRow = thead.insertRow();
const headers = ['Name', 'Age', 'City'];
headers.forEach(text => {
const th = document.createElement('th');
th.textContent = text;
headerRow.appendChild(th);
});
// 创建表格数据
const tbody = table.createTBody();
const data = [
['Alice', 24, 'New York'],
['Bob', 30, 'London'],
['Charlie', 28, 'Sydney']
];
data.forEach(rowData => {
const row = tbody.insertRow();
rowData.forEach(cellData => {
const cell = row.insertCell();
cell.textContent = cellData;
});
});
// 将表格添加到DOM
document.body.appendChild(table);
动态表格操作方法
表格创建后,可能需要动态操作行和单元格:
// 添加新行
function addRow(table, rowData) {
const row = table.insertRow();
rowData.forEach(cellData => {
const cell = row.insertCell();
cell.textContent = cellData;
});
}
// 删除指定行
function deleteRow(table, rowIndex) {
table.deleteRow(rowIndex);
}
// 更新单元格内容
function updateCell(rowIndex, cellIndex, newValue) {
const row = table.rows[rowIndex];
if (row) {
const cell = row.cells[cellIndex];
if (cell) cell.textContent = newValue;
}
}
表格排序功能实现
通过点击表头实现排序功能:
headers.forEach((header, index) => {
header.addEventListener('click', () => {
const rows = Array.from(tbody.rows);
rows.sort((a, b) => {
const valA = a.cells[index].textContent;
const valB = b.cells[index].textContent;
return isNaN(valA) ? valA.localeCompare(valB) : valA - valB;
});
rows.forEach(row => tbody.appendChild(row));
});
});
使用模板字符串生成表格
对于简单表格,可以使用模板字符串快速生成HTML:
const tableHTML = `
<table border="1">
<thead>
<tr>
${headers.map(h => `<th>${h}</th>`).join('')}
</tr>
</thead>
<tbody>
${data.map(row => `
<tr>
${row.map(cell => `<td>${cell}</td>`).join('')}
</tr>
`).join('')}
</tbody>
</table>
`;
document.body.innerHTML = tableHTML;
响应式表格实现
结合事件委托实现高效的事件处理:
table.addEventListener('click', (e) => {
const cell = e.target.closest('td');
if (cell) {
cell.contentEditable = true;
cell.focus();
}
});
table.addEventListener('blur', (e) => {
const cell = e.target.closest('td');
if (cell && cell.contentEditable) {
cell.contentEditable = false;
// 保存修改后的数据
}
}, true);
表格分页功能
实现客户端分页功能:

const itemsPerPage = 2;
let currentPage = 0;
function displayPage(page) {
tbody.innerHTML = '';
const start = page * itemsPerPage;
const pageData = data.slice(start, start + itemsPerPage);
pageData.forEach(row => addRow(tbody, row));
}
document.getElementById('next').addEventListener('click', () => {
if ((currentPage + 1) * itemsPerPage < data.length) {
currentPage++;
displayPage(currentPage);
}
});
document.getElementById('prev').addEventListener('click', () => {
if (currentPage > 0) {
currentPage--;
displayPage(currentPage);
}
});






