1. 程式人生 > 實用技巧 >使用js 建立table tr th td image 等

使用js 建立table tr th td image 等



<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
body{
width:800px;
margin:50pxauto;
}
table{
border-collapse:collapse;
width:800px;
border:1pxsolid#000000;
}
th{
border:2pxsolid;
}
td,tr{
height:30px;
line-height:30px;
border:1pxsolid#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新增一個物件屬性來儲存truefalse的多選框 //javascriptobject的屬性是根據增加的先後循序遍歷的,以下操作就相當於在price後面新增一個seleced
//data.forEach(element=>{ //element.selected=Math.floor(Math.random()*2)>0;
//}); //實現selected在id的前面使用map方法迴圈遍歷 data=data.map(t=>{ //新建一個物件 varobj={}; obj.selected=Math.floor(Math.random()*2)>0; //在把foreach遍歷的t每個物件複製給obj,data陣列物件在重新接收下 for(varkeyint){ obj[key]=t[key]; } returnobj;//返回obj });
//建立table、tr和th vartable=document.createElement('table'); vartr=document.createElement('tr'); table.appendChild(tr); for(varkeyindata[0]){ varth=document.createElement('th'); th.textContent=key; tr.appendChild(th); }

//把data陣列物件迴圈遍歷後插入到td中,並且判斷是否有圖片有圖片的要新增圖片 for(vari=0;i<data.length;i++){ vartr=document.createElement('tr'); table.appendChild(tr); for(varkeyindata[i]){ vartd=document.createElement('td'); if(key==='icon'){ varimg=newImage(); img.src=data[i].icon; td.appendChild(img);
//判斷selected }elseif(key==="selected"){ varinput=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>