首页 > 解决方案 > 如何在正在克隆的容器中附加 Button

问题描述

我创建了一个<template>标签,我给它里面有几个孩子

我正在获取一个包含一些对象的 json 文件,并在获取数据后运行 forEach 循环,以便将其更改<h1>为相等并显示 json 文件中的所有名称。我还克隆了模板,然后将克隆的模板附加到main tag.

当我尝试创建一个按钮并将其附加到内部时,问题就<div class="content"> that is located inside the template.开始<div class="content"> 了抛出此错误Uncaught (in promise) TypeError: Cannot read property 'appendChild' of null这是循环内的完整代码。

如果我尝试将此行更改 contentdiv.appendChild(btn); 为此 thisclone.appendChild(btn); 那么它可以工作,但按钮不在<div class="content">我想要的里面。

任何人都可以帮助我理解我在这里做错了什么?

const data = [{
    fullname: "George Clooney"
}, {
    fullname: "Fred Astaire"
}]

data.forEach(actor => {
  //clone the template
  const clone = template.cloneNode(true);
  //get actor name and change the content to be = to the full name inside the json obj
  const actorName = clone.querySelector('.actor-name').textContent = actor.fullname;
  const contentdiv = document.querySelector('.content');
  //create button
  const btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Read More'));
  btn.classList = 'btn'

  contentdiv.appendChild(btn);


  //apend the the clone to the main tag
  main.appendChild(clone);

});
<template id='template'>
    <div class="content">
      <h1 class="actor-name">
      </h1>

    </div>
  </template>

标签: javascripthtml

解决方案


您需要克隆内容

const data = [{
  fullname: "George Clooney"

}, {
  fullname: "Fred Astaire"

}]

const main = document.getElementById("main");

data.forEach(actor => {

  //clone the template
  const clone = document.getElementById("template").content.cloneNode(true);
  clone.querySelector('.actor-name').textContent = actor.fullname;
  const contentdiv = clone.querySelector('.content');
  const btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Read More'));
  btn.classList = 'btn'
  contentdiv.appendChild(btn);
  main.appendChild(clone);
});
<template id='template'>
    <div class="content">
      <h1 class="actor-name"></h1>
    </div>
  </template>
<div id="main"></div>


推荐阅读