js实现表
以下是几种常见的 JavaScript 表格实现方法:
动态生成表格
使用 DOM 操作动态创建表格结构:
// 创建表格元素
const table = document.createElement('table');
table.border = '1';
// 创建表头
const thead = table.createTHead();
const headerRow = thead.insertRow();
['姓名', '年龄', '城市'].forEach(text => {
const th = document.createElement('th');
th.textContent = text;
headerRow.appendChild(th);
});
// 创建表格内容
const tbody = table.createTBody();
const data = [
{name: '张三', age: 25, city: '北京'},
{name: '李四', age: 30, city: '上海'}
];
data.forEach(item => {
const row = tbody.insertRow();
Object.values(item).forEach(value => {
const cell = row.insertCell();
cell.textContent = value;
});
});
// 将表格添加到页面
document.body.appendChild(table);
使用模板字符串
通过字符串拼接生成表格 HTML:
const data = [
{id: 1, product: '手机', price: 3999},
{id: 2, product: '笔记本', price: 5999}
];
let html = `
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>商品</th>
<th>价格</th>
</tr>
</thead>
<tbody>
${data.map(item => `
<tr>
<td>${item.id}</td>
<td>${item.product}</td>
<td>${item.price}</td>
</tr>
`).join('')}
</tbody>
</table>
`;
document.body.innerHTML = html;
使用框架(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>
);
}
// 使用示例
const products = [
{id: 1, name: '键盘', stock: 50},
{id: 2, name: '鼠标', stock: 100}
];
ReactDOM.render(
<DataTable data={products} />,
document.getElementById('root')
);
表格排序功能
为表格添加点击排序功能:
function sortTable(table, column, asc = true) {
const tbody = table.tBodies[0];
const rows = Array.from(tbody.querySelectorAll('tr'));
rows.sort((a, b) => {
const aVal = a.cells[column].textContent;
const bVal = b.cells[column].textContent;
return asc ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
});
while (tbody.firstChild) {
tbody.removeChild(tbody.firstChild);
}
tbody.append(...rows);
}
// 使用示例
document.querySelectorAll('th').forEach(th => {
th.addEventListener('click', () => {
const table = th.closest('table');
const headerIndex = Array.from(th.parentNode.children).indexOf(th);
sortTable(table, headerIndex);
});
});
响应式表格
使用 CSS 和 JavaScript 实现响应式表格:
function makeTableResponsive(table) {
const headers = Array.from(table.querySelectorAll('th')).map(th => th.textContent);
const rows = table.querySelectorAll('tbody tr');
rows.forEach(row => {
const cells = row.querySelectorAll('td');
cells.forEach((cell, i) => {
cell.setAttribute('data-label', headers[i]);
});
});
}
// 调用函数
const tables = document.querySelectorAll('table');
tables.forEach(makeTableResponsive);
这些方法涵盖了从基础到进阶的表格实现方式,可以根据具体需求选择合适的实现方案。







