首页 > 解决方案 > 如何使用模板元素在 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>

标签: javascripthtml

解决方案


您需要克隆元素,然后附加:

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>


推荐阅读