使用js 创建table tr th td image 等
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
body{
width: 800px;
margin: 50px auto;
}
table{
border-collapse: collapse;
width: 800px;
border: 1px solid #000000;
}
th{
border: 2px solid;
}
td,tr{
height: 30px;
line-height: 30px;
border: 1px solid #33652f;
text-align: center;
}
img{
width: 50px;
height: 50px;
}
</style>
<script>
data=[
{id:10001,icon:"icon/1.png",name:"王玥",price:"薪资"},
{id:10002,icon:"icon/2.png",name:"杜伟 ",price:"IT"},
{id:10003,icon:"icon/3.png",name:"高冬梅",price:"人事"},
{id:10004,icon:"icon/4.png",name:"刘海波",price:"安全"},
{id:10005,icon:"icon/5.png",name:"于海燕",price:"后勤"},
{id:10006,icon:"icon/6.png",name:"夏远静",price:"经理"},
];
//给data添加一个对象属性来保存 true false 的多选框
//javascript object 的属性是根据增加的先后循序遍历的,以下操作就相当于在price后面添加一个seleced
// data.forEach(element => {
// element.selected=Math.floor(Math.random()*2)>0;
// });
//实现selected在id的前面使用map方法循环遍历
data=data.map(t => {
//新建一个对象
var obj={};
obj.selected=Math.floor(Math.random()*2)>0;
//在把foreach遍历的t每个对象复制给obj,data数组对象在重新接收下
for(var key in t){
obj[key]=t[key];
}
return obj; //返回obj
});
//创建table、tr 和th
var table=document.createElement('table');
var tr=document.createElement('tr');
table.appendChild(tr);
for(var key in data[0]){
var th=document.createElement('th');
th.textContent=key;
tr.appendChild(th);
}
//把data数组对象循环遍历后 插入到td中,并且判断 是否有图片有图片的要添加图片
for(var i=0;i<data.length;i++){
var tr=document.createElement('tr');
table.appendChild(tr);
for(var key in data[i]){
var td=document.createElement('td');
if(key==='icon'){
var img=new Image();
img.src=data[i].icon;
td.appendChild(img);
//判断selected
}else if(key==="selected"){
var input=document.createElement("input");
input.type="checkbox";
td.appendChild(input);
//修改checkbox是否被选中状态
input.checked=data[i][key];
}else{
td.textContent=data[i][key];
}
tr.appendChild(td);
}
}
//把table插入到body中
document.body.prepend(table)
</script>
</body>
</html>