编辑
2026-04-01
undefined
00

目录

template标签
实例
同步写法
异步写法

template标签

是HTML5中引入的一种新标签,用于定义可复制的模板。它允许在文档中定义一段包含HTML结构的模板,但不会在页面加载时显示其内容,加载后通过使用JavaScript来显示它。

实例

.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; }
学生列表
编号
姓名
列表
<template id="tp"> <div class="row"> <div class="col">xxx</div> <div class="col">xxx</div> <div class="col">xxx</div> </div> </template> <script> let arr = [ { id: 1, name: '张三', age: 18 }, { id: 2, name: '李四', age: 19 }, { id: 3, name: '王五', age: 20 }, ] const tp = document.getElementById('tp') const row = tp.content const [c1, c2, c3] = row.querySelectorAll('.col') const tbody = document.querySelector('.tbody') for (const { id, name, age } of arr) { c1.textContent = id c2.textContent = name c3.textContent = age const newNode = document.importNode(row, true) tbody.appendChild(newNode) } </script>

同步写法

新建students.json文件: [ { "id": 1, "name": "张三", "age": 18 }, { "id": 2, "name": "李四", "age": 19 }, { "id": 3, "name": "王五", "age": 20 } ]相应的JS代码修改为: async function getStudents() { try { // 获取响应对象,返回 Promise const res = await fetch('students.json')

// 获取响应体 const arr = await res.json() const tp = document.getElementById('tp') const row = tp.content const [c1, c2, c3] = row.querySelectorAll('.col') const tbody = document.querySelector('.tbody') for (const { id, name, age } of arr) { c1.textContent = id c2.textContent = name c3.textContent = age const newNode = document.importNode(row, true) tbody.appendChild(newNode) }

} catch (e) { console.log(e) } }

getStudents()

异步写法

相应的JS代码修改为: fetch('students.json') .then((res) => res.json()) .then((arr) => { const tp = document.getElementById('tp') const row = tp.content const [c1, c2, c3] = row.querySelectorAll('.col') const tbody = document.querySelector('.tbody')

for (const { id, name, age } of arr) { c1.textContent = id c2.textContent = name c3.textContent = age const newNode = document.importNode(row, true) tbody.appendChild(newNode) }

}) .catch((e) => console.log(e))

本文作者:a

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!