JavaScript实现自动创建表格并赋值JSON数据到单元格
2017-08-19 本文已影响679人
幻凌风
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
var bgColor;
var list = [
{ id: '1', country: '中国', capital: '北京' },
{ id: '2', country: '美国', capital: '纽约' },
{ id: '3', country: '英国', capital: '伦敦' },
{ id: '4', country: '日本', capital: '东京' },
{ id: '5', country: '韩国', capital: '首尔' },
{ id: '6', country: '法国', capital: '柏林' }
];
window.onload = function myfunction() {
var body = window.document.getElementsByTagName("body")[0];
//创建表格
var table = window.document.createElement("table");
table.border = 1;
body.appendChild(table);
//创建标题行
var thead = window.document.createElement("thead");
var itemHead = list[0];
for (var index in itemHead) {
//创建标题单元格添加到thead
var th = window.document.createElement("th");
th.innerText = index;
thead.appendChild(th);
}
table.appendChild(thead);
//遍历对象,创建行和单元格
for (var i = 0; i < list.length; i++) {
var item = list[i];
//创建行
var tr = window.document.createElement("tr");
if (i % 2 == 0) {
tr.style.backgroundColor = "red";
} else {
tr.style.backgroundColor = "blue";
}
//注册指向行的事件
tr.onmouseover = function () {
bgColor = this.style.backgroundColor;
this.style.backgroundColor = "green";
}
tr.onmouseout = function () {
this.style.backgroundColor = bgColor;
}
table.appendChild(tr);
for (var key in item) {
//创建单元格
var td = window.document.createElement("td");
td.innerText = item[key];
tr.appendChild(td);
}
}
}
</script>
</head>
<body>
</body>
</html>