不是 Template tag content is empty 的副本- Angular 中的错误,而我的问题是关于 Vanilla Js。
我正在研究 ThingsBoard小部件。在 the HTML tab ,我有这个简单的模板:
<template id="myTemplate">
<div>Test</div>
</template>
在 JS 选项卡中,我试图获取此模板的内容(最终克隆它):
const template = document.querySelector("#myTemplate");
console.log(template.content);
但是,我得到一个空 DocumentFrgament
:
这很奇怪,因为当我在 ThingsBoard 之外运行它时(例如这里的 StackOverflow 片段),我确实得到了模板的内容:
const template = document.querySelector("#myTemplate");
console.log(template.content);
<template id="myTemplate">
<div>Test</div>
</template>
有什么想法吗?
最佳答案
如果您的 ThingsBoard 示例使用的是 React 或类似的 DOM 库,它可能会以编程方式创建 DOM,这可能会导致此问题。
当 <template>
使用 appendChild
以编程方式构建, content
仍然是空的。
例如:
const template = document.createElement('template');
template.appendChild(document.createElement('div'));
console.log(template.content); // #document-fragment (empty)
而不是 template.appendChild
, 你必须使用 template.content.appendChild
使其正常工作。
我希望这对您有所帮助!
关于javascript - 模板内容是一个空文档片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70677604/