<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style scoped>
div {
font-family: 华文行楷;
font-size: 20px;
}
.title {
margin-bottom: 10px;
font-size: 30px;
color: #333;
text-align: center;
}
.row {
background-color: #fff;
display: flex;
justify-content: center;
}
.col {
border: 1px solid #f0f0f0;
width: 15%;
height: 35px;
text-align: center;
line-height: 35px;
}
.bold .col {
background-color: #f1f1f1;
}
</style>
</head>
<body>
<div>
<div class="title">学生列表</div>
<div class="thead">
<div class="row bold">
<div class="col">编号</div>
<div class="col">姓名</div>
<div class="col">性别</div>
<div class="col">年龄</div>
</div>
</div>
<div class="tbody">
</div>
</div>
<template id="tp">
<div class="row">
<div class="col">xx</div>
<div class="col">xx</div>
<div class="col">xx</div>
<div class="col">xx</div>
</div>
</template>
<script>
//这里的数据以后为后端程序提供
let students=[
{id:1,name:"刘备",sex:"男",age:20},
{id:2,name:"大乔",sex:"女",age:18}
];
const tp=document.querySelector("#tp");
const row=tp.content;
const [r1,r2,r3,r4]=row.querySelectorAll(".col");
const tbody=document.querySelector(".tbody");
for (const {id,name,sex,age} of students){
r1.textContent=id;
r2.textContent=name;
r3.textContent=sex;
r4.textContent=age;
//复制元素
const newRow=document.importNode(row,true)
//插入节点
tbody.appendChild(newRow);
}
</script>
</body>
</html>
4-JS利用模板
于 2022-11-20 18:32:37 首次发布