javascript - 如何使用模板元素在 HTML 中显示对象数组
问题描述
我正在尝试使用模板元素将对象数组添加到 HTML 页面。我添加了它,但发现只有最后一个对象被正确添加到 HTML 中。我犯了什么错误?我应该如何纠正它?我也试过用'createElement'方法来做,没关系。谢谢
let array = [
{
city: 'Rome',
country: 'Italy'
},
{
city: 'Moscow',
country: 'Russia'
}
];
const template = document.querySelector('#template');
const clone = template.content.cloneNode(true);
const listElement = clone.querySelector('.template-list');
const lists = document.querySelector('.lists');
array.forEach(i => {
listElement.querySelector('.template-city').textContent = i.city;
listElement.querySelector('.template-country').textContent = i.country;
lists.append(listElement);
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul class="lists">
</ul>
<template id="template">
<li class="template-list">
<p class="template-city"></p>
<p class="template-country"></p>
</li>
</template>
<script src="./script.js"></script>
</body>
</html>
解决方案
您需要克隆元素,然后附加:
let array = [{
city: 'Rome',
country: 'Italy'
},
{
city: 'Moscow',
country: 'Russia'
}
];
const template = document.querySelector('#template');
const clone = template.content.cloneNode(true);
const listElement = clone.querySelector('.template-list');
const lists = document.querySelector('.lists');
array.forEach(i => {
let newClone = listElement.cloneNode(true)
newClone.querySelector('.template-city').textContent = i.city;
newClone.querySelector('.template-country').textContent = i.country;
lists.append(newClone);
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul class="lists"></ul>
<template id="template">
<li class="template-list">
<p class="template-city"></p>
<p class="template-country"></p>
</li>
</template>
<script src="./script.js"></script>
</body>
</html>
推荐阅读
- debian-buster - 如何在 debian 10 上安装 AMD radeon PRO WX 4100 的驱动程序?
- python - 多个 Python 绘图未在其他子图中显示绘图
- android - Android动态功能卡在安装视图虽然它说它已安装
- c# - 将按钮绑定到子组件 blazor
- c - C中的FILENAME_MAX和PATH_MAX有什么区别吗?
- node.js - 是什么导致在docker中使用节点出现以下错误
- php - PDO $_GET 当用户单击该任务的删除按钮时删除数据库中特定任务的任务ID
- python - Plotly:如何为具有完全不同数据和布局的图形制作一个绘图下拉菜单?
- performance - sqlalchemy 延迟列加载 - 似乎没有任何效率
- html - css 中的 SVG Sprite 声明的背景图像