js 动态创建table
时间: 2023-10-04 08:11:41 浏览: 44
可以通过以下代码动态创建一个 table 元素:
```javascript
// 创建 table 元素
var table = document.createElement('table');
// 创建表头
var thead = document.createElement('thead');
var tr = document.createElement('tr');
var th1 = document.createElement('th');
th1.innerHTML = '列1';
var th2 = document.createElement('th');
th2.innerHTML = '列2';
tr.appendChild(th1);
tr.appendChild(th2);
thead.appendChild(tr);
// 创建表格内容
var tbody = document.createElement('tbody');
for (var i = 0; i < 5; i++) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
td1.innerHTML = '行' + (i + 1) + '列1';
var td2 = document.createElement('td');
td2.innerHTML = '行' + (i + 1) + '列2';
tr.appendChild(td1);
tr.appendChild(td2);
tbody.appendChild(tr);
}
// 将表头和表格内容添加到 table 中
table.appendChild(thead);
table.appendChild(tbody);
// 将 table 添加到页面中
document.body.appendChild(table);
```
上述代码会创建一个包含表头和表格内容的 table 元素,并将其添加到页面中。你可以根据需要自定义表头和表格内容的样式和内容。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)