最详细的JS动态创建表格以及实现分页!
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
// 创建表格的函数
function createTable(data) {
// 获取body元素
const body = document.body;
// 创建表格
const table = document.createElement('table');
table.border = 1;
// 创建表头
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
data[0].forEach((header) => {
const th = document.createElement('th');
th.innerText = header;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// 创建表身
const tbody = document.createElement('tbody');
data.forEach((rowData, rowIndex) => {
const row = document.createElement('tr');
rowData.forEach((cellData) => {
const cell = document.createElement('td');
cell.innerText = cellData;
row.appendChild(cell);
});
tbody.appendChild(row);
});
table.appendChild(tbody);
// 将表格添加到body中
body.appendChild(table);
}
// 示例数据
const sampleData = [
['Name', 'Age', 'Country'],
['Alice', 25, 'USA'],
['Bob', 30, 'UK'],
// ...更多数据
];
// 调用函数创建表格
createTable(sampleData);
这段代码展示了如何使用JavaScript动态创建一个简单的HTML表格。首先,我们定义了一个createTable
函数,它接受一个数组作为参数,该数组代表表格的数据。函数内部,我们使用DOM操作创建了table
、thead
、tbody
等元素,并填充了相应的数据。最后,我们将表格添加到页面的body
元素中。这个例子简单明了,展示了如何使用JavaScript处理表格数据并创建交互式表格。
评论已关闭