将学生信息写入js数组,再使用for循环遍历渲染到页面。
效果图:
全代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<title>Document</title>
</head>
<style>
table{
width: 600px;
text-align: center;
}
table,th,td{
border: 1px solid#ccc;
border-collapse: collapse;
}
caption{
margin-bottom: 20px;
font-size: 20px;
}
tr{
height: 40px;
cursor: pointer;
}
table tr:nth-child(1){
background-color: #ddd;
}
table td:not(:first-child):hover{
background-color: #eee;
}
</style>
<body>
<h2>学生信息</h2>
<table>
<caption>学生列表</caption>
<tr>
<td>序号</td>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
<td>家乡</td>
</tr>
<script>
let student = [
{name:'小刚',age:18,gender:'男',hometown:'湖北'},
{name:'小红',age:19,gender:'女',hometown:'东北'},
{name:'小明',age:18,gender:'男',hometown:'湖北'},
{name:'小原',age:21,gender:'男',hometown:'安溪'},
{name:'那由多',age:16,gender:'女',hometown:'日本'}
]
for(let i=0;i<student.length;i++){
document.write(`
<tr>
<td>${i+1}</td>
<td>${student[i].name}</td>
<td>${student[i].age}</td>
<td>${student[i].gender}</td>
<td>${student[i].hometown}</td>
</tr>
` )
}
</script>
</table>
</body>
</html>