<!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>
JavaScript实现自动创建表格并赋值JSON数据到单元格
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 1.背景图片大小:1024*768 2.改变状态栏字体 3.创建modal保存数据 4.取消单元格选中灰色 5.查...