0

我正在尝试将文档片段的内容(在纯 javascript 中)插入到 DOM 元素中。工作原理是这样的:

var a = document.getElementById("a"),
    b = document.getElementById("b");

现在我使用模板元素将“a”的内容放入文档片段

var content = document.createElement("template");
content.innerHTML = a.innerHTML;
content = content.content.cloneNode(true);

现在我想bcontent. 我尝试了一个简单的b.innerHTML = content.innerHTML;,但似乎文档片段没有innerHTML属性。
这可能吗?

注意:我知道这完全是一种无效的方式来完成制作任务b.innerHTML = a.innerHTML,但显然这只是我正在设法完成的更大任务的简化。

4

1 回答 1

1

您需要创建“克隆”,然后通过使用模板内容属性,您可以ab片段中使用内部 HTML。

例子:

const a = document.getElementById("a"),
  b = document.getElementById("b");

// note template will only be parsed, to render it use js...

function initTemplate() {

  const container = document.getElementById("container");
  const template = document.getElementById("t");

  // create a first clone with the innerHTML of a...

  const firstClone = template.content.cloneNode(true);
  firstClone.textContent = a.innerHTML;

  // create a second clone with the innerHTML of b...

  const secondClone = template.content.cloneNode(true);
  secondClone.textContent = b.innerHTML;

  // append to the document

  container.appendChild(firstClone);
  container.appendChild(secondClone);


}
<p id="a">Paragraph A</p>
<p id="b">Paragraph B</p>
<button onclick="initTemplate()">Init Template</button>

<br>
<div id="container"></div>

<template id="t">
  
</template>

如果您想检查您的浏览器是否支持HTML template element,请执行以下操作:

if ("content" in document.createElement("template") {

   // clone the elements as above and append them to the document

}

Mozilla 文档Mozilla 文档

于 2020-12-21T08:52:13.527 回答