多次附加 template.content.cloneNode(true) 无效
Appending template.content.cloneNode(true) multiple times not working
这不起作用:
let template = document.getElementById("template");
const templateContentCloned = template.content.cloneNode(true);
document.getElementById("div1").appendChild(templateContentCloned);
document.getElementById("div2").appendChild(templateContentCloned);
document.getElementById("div3").appendChild(templateContentCloned);
<template id="template">
<p>Here is my paragraph.</p>
</template>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
但是这样做:
let template = document.getElementById("template");
const templateContent = template.content;
document.getElementById("div1").appendChild(templateContent.cloneNode(true));
document.getElementById("div2").appendChild(templateContent.cloneNode(true));
document.getElementById("div3").appendChild(templateContent.cloneNode(true));
<template id="template">
<p>Here is my paragraph.</p>
</template>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
为什么?为什么每次要用模板都要克隆节点?
template.content
包含一个 documentFragment
它只能插入到 DOM 一次:
A common use for DocumentFragment is to create one, assemble a DOM subtree within it, then append or insert the fragment into the DOM
using Node interface methods such as appendChild() or insertBefore().
Doing this moves the fragment's nodes into the DOM, leaving behind an
empty DocumentFragment
所以在它被插入到div1
变量之后templateContentCloned
变成了一个空的documentFragment
hens nothing inserted into div2
and div3
这不起作用:
let template = document.getElementById("template");
const templateContentCloned = template.content.cloneNode(true);
document.getElementById("div1").appendChild(templateContentCloned);
document.getElementById("div2").appendChild(templateContentCloned);
document.getElementById("div3").appendChild(templateContentCloned);
<template id="template">
<p>Here is my paragraph.</p>
</template>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
但是这样做:
let template = document.getElementById("template");
const templateContent = template.content;
document.getElementById("div1").appendChild(templateContent.cloneNode(true));
document.getElementById("div2").appendChild(templateContent.cloneNode(true));
document.getElementById("div3").appendChild(templateContent.cloneNode(true));
<template id="template">
<p>Here is my paragraph.</p>
</template>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
为什么?为什么每次要用模板都要克隆节点?
template.content
包含一个 documentFragment
它只能插入到 DOM 一次:
A common use for DocumentFragment is to create one, assemble a DOM subtree within it, then append or insert the fragment into the DOM using Node interface methods such as appendChild() or insertBefore(). Doing this moves the fragment's nodes into the DOM, leaving behind an empty DocumentFragment
所以在它被插入到div1
变量之后templateContentCloned
变成了一个空的documentFragment
hens nothing inserted into div2
and div3