把json中的数据显示到表格中:
/*多个对象表现形式*/
var person =
[
{"id":0,"name":"ding","hobby":['打飞机','躺赚','跟宗哥装B']},
{"id":1,"name":"chang","hobby":['打飞机','躺赚','喝酒']},
{"id":2,"name":"jiang","hobby":['打飞机','躺赚','写代码']}
]
/*单个对象表现形式
var person = {
"id":1,
"name":"丁",
"hobby":['打飞机','躺赚','写代码']
}
*/
/*
var person = {
person:[
{"id":0,"name":"ding","hobby":['打飞机','躺赚','跟宗哥装B']},
{"id":1,"name":"chang","hobby":['打飞机','躺赚','喝酒']},
{"id":2,"name":"jiang","hobby":['打飞机','躺赚','写代码']}
]
}*/
/*
{}都是以键值对的形式存在的
*/
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="person.js"></script>
<style type="text/css">
.myDiv{
width: 500px;
height: 500px;
}
td{
border:1px solid black;
}
tr{
text-align: center;
}
</style>
<script type="text/javascript">
function load(){
//:拿到tbody
var tbody = document.getElementById("myTbody");
console.log(tbody);
//:遍历对象数组
for(var p in person){ //p就是属性名
/*
如果person里面装的是对象,那么p就代表该对象的属性;
如果person里面装的是对象数组,那么p就代表该数组中的一个对象*/
//->创建tr并添加单选框
var tr = document.createElement("tr");
var sel = document.createElement("td");
sel.innerHTML = "<input type='checkbox' name='selItem'>"
tr.appendChild(sel);
//:添加对象到表格
for(var v in person[p]){
//->创建对象对应属性td
var td = document.createElement("td");
td.innerHTML = person[p][v];
//->添加到tr中
tr.appendChild(td);
}
//->添加到tbody中
tbody.appendChild(tr);
}
}
//:全选
function selAll(obj){
var status = obj.checked;
var nodeList = document.getElementsByName("selItem");
for (var i=0;i<nodeList.length;i++){
var item = nodeList[i];
if (item.checked != status)
item.checked = status;
}
}
</script>
</head>
<body onload="load()">
<div class="myDiv">
<table>
<thead>
<th>全选<input type="checkbox" onclick="selAll(this)"></th>
<th>编号</th>
<th>姓名</th>
<th>爱好</th>
</thead>
<tbody id="myTbody"></tbody>
</table>
</div>
</body>