用js实现动态添加删除表格数据_css
代码如下:

<!DOCTYPE HTML>
<html>
<head>
<meta charset = "UTF-8">
<title>table</title >
<style>
table {
margin:auto;
width: 60%;
border: 1px solid black;
border-collapse: collapse;
}

table caption {
color: blue;
font: 34px consolas bold;
}

table th, table td {
border: 1px solid black;
text-align:center;
}

table th {
font: 20px consolas bold;
background-color: gray;
}

table tr:nth-child(n+2){
background-color: cyan;
}

table tr:nth-child(2n+2) {
background-color: red;
}
</style>
<script>
var data = [
{id: "001", fullname: "张三", sex: "男", score: [98,33,48]},
{id: "002", fullname: "李四", sex: "w", score: [11,22,33]},
{id: "003", fullname: "kyo", sex: "m", score: [22,33,55]},
{id: "004", fullname: "yamazaki", sex: "w", score: [99, 100, 80]}
];

var Student = function (id, fullname, sex, score)
{
this.id = id;
this.fullname = fullname;
this.sex = sex;
this.score = score;
}

var Score = function (chinese, math, english)
{
this.chinese = chinese;
this.math = math;
this.english = english;
}

var students = [];
for (var i = 0; i <data.length; i++)
{
var d = data[i];
var s = d["score"];
students.push(new Student (d["id"], d["fullname"], d["sex"], new Score(s[0], s[1], s[2])));
}

onload = function ()
{
var table = document.createElement("table");
var tbody = document.createElement("tbody");
table.appendChild(tbody);
var caption = table.createCaption();
caption.innerHTML = "学生成绩表";
var tr = tbody.insertRow (0);
var str = "学号,姓名,性别,语文,数学,英语,操作".split(",");
for (var i = 0; i <str.length; i++)
{
var th = document.createElement("th");
th.innerHTML = str[i];
tr.appendChild (th);
}
for (var i = 0; i <students.length; i++)
{
var tr = tbody.insertRow (tbody.rows.length);
var obj = students[i];
for (var p in obj)
{
var op = obj[p];
if (p != "score")
{
var td = tr.insertCell (tr.cells.length);
td.innerHTML = op;
}
else
{
for (var p in op)
{
var td = tr.insertCell (tr.cells.length);
td.innerHTML = op[p];
}
}
}
//下面为每行末尾添加删除按钮
var delCell = document.createElement('td');//创建操作列
tr.appendChild(delCell);
var btnDel = document.createElement('input'); //创建一个input控件
btnDel.setAttribute('type','button'); //type="button"
btnDel.setAttribute('value','删除');
btnDel.setAttribute('onclick', 'delRow(this)');
delCell.appendChild(btnDel); //把删除按钮加入td,别忘了
}
document.body.appendChild(table);
}

//删除操作
function delRow(obj){
if(confirm("确定删除这一行嘛?")){
//找到按钮所在行的节点,然后删掉这一行
obj.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode);
//btnDel - td - tr - tbody - 删除(tr)
//刷新网页还原。实际操作中,还要删除数据库中数据,实现真正删除
}

}

</script>
<body >

</body>
</html>