js 将js中数据动态渲染到html页面
css代码
<style>
*{
margin: 0;
padding: 0;
}
table{
width: 300px;
text-align: center;
}
</style>
html代码
<table border="1" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<!--js渲染-->
</tbody>
</table>
js代码
<script>
//提前准备好的数据
var users=[
{id:1,name:'张三',age:18},
{id:2,name:'李四',age:21},
{id:3,name:'王五',age:36}
]
//0.获取tbody标签
var tbody=document.querySelector('tbody')
//1.循环遍历users数据
users.forEach(function(item){
//这里的item就是数组中的每一个对象
console.log(item)
//2.每一个对象生成一个tr标签
var tr=document.createElement('tr')
//3.循环遍历item
for(var key in item){
//4.生成td标签
var td=document.createElement('td')
td.innerHTML=item[key]
//5.把td插入到tr内部
tr.appendChild(td)
}
//6.把本次的tr插入到tbody内部
tbody.appendChild(tr)
})
</script>