一、搭建HTML模板
首先先自己搭建一个HTML模板,把自己想要实现的结构模拟出来
比如这里需要打印的用户输入的学生信息有以下几个属性
<table>
<caption>学生列表</caption>
<thead>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>家乡</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>小明</td>
<td>18</td>
<td>男</td>
<td>河北省</td>
</tr>
</tbody>
</table>
二、使用CSS给上面的表格添加样式
table {
width: 500px;
margin: 100px auto;
border-collapse: collapse;
text-align: center;
}
table caption {
margin-bottom: 10px;
font-weight: 700;
}
thead {
height: 60px;
background-color: #ccc;
}
tr {
height: 60px;
}
th,
td {
border: 1px solid #000;
}
添加完样式之后将html代码删除或注释掉
<!-- <table>
<caption>学生列表</caption>
<thead>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>家乡</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>小明</td>
<td>18</td>
<td>男</td>
<td>河北省</td>
</tr>
</tbody>
</table> -->
三、使用js创建一个数组,用来存储学生信息,学生信息使用对象存储
// 用来存储学生信息的空数组
let students = []
//让用户选择操作内容
while (true) {
let res = +prompt(`
请选择操作:
1.输入学生信息
2.结束(结束之后打印学生信息表格)
`
)
//当用户输入2时,结束循环
if (res === 2) {
break
}
//弹出输入框提示用户输入学生信息
else {
let student = {}
student.name = prompt("请输入学生的姓名")
student.age = prompt("请输入学生的年龄")
student.gender = prompt("请输入学生的性别")
student.hometown = prompt("请输入学生的家乡")
students.push(student)
}
}
使用js将学生列表打印渲染到页面中
document.write(`<table>
<caption>学生列表</caption>
<thead>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>家乡</th>
</thead>
<tbody>`)
for (let i = 0; i < students.length; i++) {
document.write(`<tr>
<td>${i + 1}</td>
<td>${students[i].name}</td>
<td>${students[i].age}</td>
<td>${students[i].gender}</td>
<td>${students[i].hometown}</td>
</tr>`)
}
document.write(`</tbody>
</table>`)
四、最终页面效果
目录
三、使用js创建一个数组,用来存储学生信息,学生信息使用对象存储