js 初始化table示例
时间: 2023-07-08 11:06:33 浏览: 137
以下是使用 JavaScript 初始化表格的示例代码:
```html
<table id="myTable">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>25</td>
<td>男</td>
</tr>
<tr>
<td>李四</td>
<td>30</td>
<td>男</td>
</tr>
<tr>
<td>王五</td>
<td>28</td>
<td>女</td>
</tr>
</tbody>
</table>
<script>
// 获取表格元素
const table = document.getElementById('myTable');
// 获取表头和表体
const thead = table.querySelector('thead');
const tbody = table.querySelector('tbody');
// 获取表头中的列数
const columnCount = thead.rows[0].cells.length;
// 将表格中的每一行转换为数组
const rows = Array.from(tbody.rows).map(row => Array.from(row.cells));
// 创建一个新的表格
const newTable = document.createElement('table');
// 创建表头
const newThead = document.createElement('thead');
const newRow = document.createElement('tr');
for (let i = 0; i < columnCount; i++) {
const newCell = document.createElement('th');
newCell.textContent = `列 ${i+1}`;
newRow.appendChild(newCell);
}
newThead.appendChild(newRow);
// 创建表体
const newTbody = document.createElement('tbody');
rows.forEach(row => {
const newRow = document.createElement('tr');
row.forEach(cell => {
const newCell = document.createElement('td');
newCell.textContent = cell.textContent;
newRow.appendChild(newCell);
});
newTbody.appendChild(newRow);
});
// 将新的表头和表体添加到新的表格中
newTable.appendChild(newThead);
newTable.appendChild(newTbody);
// 替换原来的表格
table.parentNode.replaceChild(newTable, table);
</script>
```
这个示例代码将原始表格的每行都转换为一个数组,然后创建一个新的表格来显示这些数组。在这个新表格中,表头中的列名是自动生成的,为“列 1”、“列 2”等等。你可以按照自己的需求修改这个代码来满足你的需求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)