javascript - 如何在正在克隆的容器中附加 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>
解决方案
您需要克隆内容
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>
推荐阅读
- python - 如何使用python获取具有进程名称的应用程序名称?
- javascript - 我如何修改使用相同类的列的单元格数据列中的所有类都具有相同的类
- algorithm - 有没有一种方法可以有效地计算任意基数中的两个的能力?
- security - GPG 密钥 vs ssh 密钥 vs 个人访问令牌
- c# - EDI 解串器不能以不同的格式工作
- reactjs - TypeError:无法读取未定义的属性(读取“toLocaleString”)
- angular - TypeError:无法读取未定义的属性(读取“粉丝”)
- reactjs - setStates 序列在 api 调用中不起作用,为什么?
- c++ - 如何组织大型 CMakeList 文件
- python - 比较两个 defaultiddicts 并仅保留满足条件的记录