JavaScript 动态生成表格是指使用 JavaScript 在网页上实时创建和修改表格内容。后台获取数据通常涉及服务器端编程,通过 API 请求将数据发送到前端。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic Table</title>
</head>
<body>
<div id="table-container"></div>
<script>
function createTable(data) {
const container = document.getElementById('table-container');
const table = document.createElement('table');
const thead = document.createElement('thead');
const tbody = document.createElement('tbody');
// Create header row
const headerRow = document.createElement('tr');
Object.keys(data[0]).forEach(key => {
const th = document.createElement('th');
th.textContent = key;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
// Create body rows
data.forEach(item => {
const row = document.createElement('tr');
Object.values(item).forEach(value => {
const cell = document.createElement('td');
cell.textContent = value;
row.appendChild(cell);
});
tbody.appendChild(row);
});
table.appendChild(thead);
table.appendChild(tbody);
container.appendChild(table);
}
// Example data
const data = [
{ Name: 'Alice', Age: 24 },
{ Name: 'Bob', Age: 27 },
{ Name: 'Charlie', Age: 22 }
];
createTable(data);
</script>
</body>
</html>
const express = require('express');
const app = express();
const port = 3000;
app.get('/api/data', (req, res) => {
const data = [
{ Name: 'Alice', Age: 24 },
{ Name: 'Bob', Age: 27 },
{ Name: 'Charlie', Age: 22 }
];
res.json(data);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
原因:可能是数据量过大或网络延迟。
解决方法:
原因:CSS 样式未正确应用或冲突。
解决方法:
原因:代码逻辑错误或浏览器兼容性问题。
解决方法:
通过以上方法,可以有效解决动态生成表格过程中遇到的常见问题。
领取专属 10元无门槛券
手把手带您无忧上云