Sip*_*ipo 3 html javascript thingsboard
模板标签内容的重复项不是空的- Angular 中的一个错误,而我的问题是关于 Vanilla Js 的。
我正在开发ThingsBoard小部件。在HTML 选项卡中,我有这个简单的模板:
<template id="myTemplate">
<div>Test</div>
</template>
Run Code Online (Sandbox Code Playgroud)
在 JS 选项卡中,我尝试获取此模板的内容(最终克隆它):
const template = document.querySelector("#myTemplate");
console.log(template.content);
Run Code Online (Sandbox Code Playgroud)
但是,我得到一个空的 DocumentFrgament:

这很奇怪,因为当我在 ThingsBoard 之外运行它时(例如在 StackOverflow 代码片段上),我确实获得了模板的内容:
<template id="myTemplate">
<div>Test</div>
</template>
Run Code Online (Sandbox Code Playgroud)
const template = document.querySelector("#myTemplate");
console.log(template.content);
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
如果您的 ThingsBoard 示例使用 React 或类似的 DOM 库,它可能会以编程方式创建 DOM,这可能会导致此问题。
<template>当使用以编程方式构造a 时appendChild,acontent保持为空。例如:
const template = document.createElement('template');
template.appendChild(document.createElement('div'));
console.log(template.content); // #document-fragment (empty)
Run Code Online (Sandbox Code Playgroud)
template.appendChild您必须使用来代替,template.content.appendChild它才能正常工作。
我希望这能以某种方式有所帮助!