html:<div id="data"> </div>
一个空的id为data的div
style:
table{500px;border-collapse:collapse;text-align:center;}
tr:hover{background-color: #ddd;}
td{border:1px solid #ccc;height: 30px;}
thead td{font-weight:bold;}
a{display: inline-block;border: 1px solid red;color: black;font-size: 13px;height: 20px;text-align: center;line-height: 20px;}
a:hover{color: blueviolet;border: none;}
button{border: 1px solid black;margin-top: 10px; 50px;height: 20px;}
label{display: block;margin-bottom: 10px; margin-top: 10px;}
label input{margin-right: 10px;}
简单的写一点CSS
js:
var data=[
{"id":1,"name":'陈一',"arith":99,"language":90,"english":80},
{"id":2,"name":'黄二',"arith":100,"language":85,"english":90},
{"id":3,"name":'张三',"arith":60,"language":100,"english":75},
{"id":4,"name":'李四',"arith":89,"language":99,"english":100},
{"id":5,"name":'王五',"arith":79,"language":80,"english":65},
{"id":6,"name":'赵六',"arith":69,"language":79,"english":99},
{"id":7,"name":'钱七',"arith":60,"language":52,"english":100},
{"id":8,"name":'孙八',"arith":55,"language":60,"english":80},
{"id":9,"name":'杨九',"arith":70,"language":89,"english":66},
{"id":10,"name":'吴十',"arith":100,"language":55,"english":52},
];
function initTable(){
var table=document.createElement("table"); //创建空table对象
var thead=table.createTHead();//在table中添加thead
var tr=thead.insertRow();//在thead中添加一行tr
for(tr.insertCell().innerHTML in data[0]);//遍历data数组中第1个对象的所有属性,并添加到thead
tr.insertCell().innerHTML="total";
tr.insertCell().innerHTML="operation";
var tbody=table.createTBody(); //在table中添加tbody
for(var i=0;i<data.length;i++){ //遍历data数组中每个商品对象,并在tbody中添加tr
var tr=tbody.insertRow();
for(var key in data[i]){//遍历当前商品对象的所有属性
tr.insertCell().innerHTML=data[i][key];//在tr中添加td,并设置td的数据
}
var total=data[i].arith+data[i].language+data[i].english;
tr.insertCell().innerHTML=total;
var btn=document.createElement("a");//创建 a元素标签 为删除按钮
btn.innerHTML="删除";
tr.insertCell().appendChild(btn);//为每行多增加一个td,其中放一个按钮
btn.onclick=function(){//为删除按钮绑定点击onclick事件
var tr=this.parentNode.parentNode;//找到按钮所在行(tr)
tr.parentNode.removeChild(tr);//删除该行
}
}
document.getElementById("data").appendChild(table);//将table对象追加到id为data的div中
}
window.onload=function(){
initTable();
}
JS部分:先定义了一个数组对象,然后依次的按照table结构去细化table里面的东西
效果图对比: