是HTML5中引入的一种新标签,用于定义可复制的模板。它允许在文档中定义一段包含HTML结构的模板,但不会在页面加载时显示其内容,加载后通过使用JavaScript来显示它。
<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 许可协议。转载请注明出处!