<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="box"></div>
<script>
//模拟数据
var headDates = ['姓名','科目','分数','操作']
var dates = [{name: 'zs',subject:'数学',score: 90},
{name: 'zs',subject:'数学',score: 90},
{name: 'zs',subject:'数学',score: 90},
{name: 'zs',subject:'数学',score: 90},
{name: 'zs',subject:'数学',score: 90},]
//创建table元素 放在box中
var table = document.createElement('table')
var box = document.getElementById('box')
box.appendChild(table)
//设置表格属性
table.style.border = '1px'
table.style.borderColor = 'blue'
table.style.borderSolid = 'solid'
// table.style.height = '40px'
table.style.width = '600px'
// table.style.backgroundColor = 'red'
//创建头部元素thead 放在table中
var thead = document.createElement('thead')
table.appendChild(thead)
var tr = document.createElement('tr')
thead.appendChild(tr)
//遍历th元素
for(var i=0; i<headDates.length; i++) {
var th = document.createElement('th')
th.style.height = '40px'
th.style.backgroundColor = 'yellow'
tr.appendChild(th)
th.innerText = headDates[i]
}
//创建tbody元素 放到table中
var tbody = document.createElement('tbody')
table.appendChild(tbody)
//遍历tr元素
for (var i=0; i<dates.length; i++) {
var tr = document.createElement('tr')
tbody.appendChild(tr)
var bt = dates[i]
for(k in bt) {
var td = document.createElement('td')
td.style.textAlign = 'center'
td.style.height = '40px'
td.style.backgroundColor = 'red'
tr.appendChild(td)
td.innerText = bt[k]
}
//删除事件
var td = document.createElement('td')
tr.appendChild(td)
td.style.textAlign = 'center'
td.style.height = '40px'
td.style.backgroundColor = 'red'
var del = document.createElement('a')
//删除默认行为
del.href = 'javascript:void(0)'
td.appendChild(del)
del.innerText = '删除'
//绑定按钮。点击按钮 触发事件
del.onclick = fn
}
function fn () {
tbody.removeChild(this.parentNode.parentNode)
}
</script>
</body>
</html>
如何使用js动态创建表格?
最新推荐文章于 2024-10-01 19:00:00 发布
本文将介绍如何利用JavaScript在网页中动态创建表格,包括设置表格结构、填充数据以及应用CSS样式,帮助你实现交互式的网页表格功能。
摘要由CSDN通过智能技术生成