JavaScript动态创建表格
作者:互联网
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态创建表格练习</title>
<!-- <script src="js包/common.js"></script> -->
</head>
<body>
<div id="box">
</div>
</body>
</html>
<script>
var data=[
{name:"傅红雪",subject:"数学",score:"89"},
{name:"叶开",subject:"语文",score:"55"},
{name:"公子羽",subject:"政治",score:"44"},
{name:"花无缺",subject:"美术",score:"23"},
],
theadData=["姓名","科目","成绩","操作"];
var div=document.getElementById("box");
var table=document.createElement("table");
table.width="200px";
table.height="200px";
table.border="1px";
table.style.borderCollapse="collapse";
div.appendChild(table);
var thead=document.createElement("thead");
table.appendChild(thead);
var tr=document.createElement("tr");
thead.appendChild(tr);
for (var i = 0; i < theadData.length; i++) {
var th=document.createElement("th");
tr.appendChild(th);
// setInnerText(th,theadData[i]);
th.innerText=theadData[i];
}
//创建其他行
var tbody=document.createElement("tbody");
table.appendChild(tbody);
for (var i = 0; i < data.length; i++) {
datas=data[i];
var tr=document.createElement("tr");
tbody.appendChild(tr);
for (var key in datas) {
var td=document.createElement("td");
tr.appendChild(td);
// setInnerText(td,datas[key]);
td.innerText=datas[key];
}
//删除行
// var tr=document.createElement("tr");
// tbody.appendChild(tr);
var td=document.createElement("td");
tr.appendChild(td);
var a=document.createElement("a");
a.href="#";
td.appendChild(a);
// setInnerText(a,"删除");
a.innerText="删除";
a.onclick=link;
}
function link() {
tr=this.parentNode.parentNode;
tbody.removeChild(tr);
}
</script>
效果图
标签:appendChild,创建表格,JavaScript,tr,table,var,createElement,document,动态 来源: https://blog.csdn.net/M_X_B_MR_L/article/details/121803458