【发布时间】:2017-03-06 03:39:48
【问题描述】:
我正在创建两个自定义元素,它们都使用链接 rel="import" 添加到 index.html。一个是带有插槽的容器,另一个是在插槽中放入数字的东西。这两个元素都有一个带有模板的 HTML 文件和一个指向将它们定义为自定义元素的 js 文件的链接。要将自定义元素类声明链接到我正在使用的 HTML 模板:
class PuzzlePiece extends HTMLElement{
constructor(){
super();
console.dir(document.currentScript);
const t = document.currentScript.ownerDocument.getElementById('piece-puzzle');
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(t.content.cloneNode(true));
}
这个拼图元素和容器正确渲染,当您手动将它们放入 index.html 光 dom 时,它们都可以正常工作
<special-puzzle id="grid">
<puzzle-piece id="hello"></puzzle-piece>
</special-puzzle>
但是,一旦我尝试在 index.html 中使用 JS 创建和附加拼图:
<script>
const addToGrid = document.createElement("puzzle-piece");
document.getElementById("grid").appendChild(addToGrid);
</script>
我在特殊拼图 light dom 中看到一个新拼图,但它不占用插槽,不渲染,并且控制台出现错误:
未捕获的类型错误:无法读取 null 的属性“内容” 在新的 PuzzlePiece (puzzle-piece.ts:8) 在 HTMLDocument.createElement (:3:492) 在(索引):37
据我所知,问题是在使用 document.createElement 时,浏览器正在访问类定义,但 document.currentScript.ownerDocument 与仅手动使用 HTML 标记时不同。我相信正因为如此,组件找不到它的模板。这是我的第一个 Stack Overflow 问题,因此我们将不胜感激任何反馈/帮助!
【问题讨论】:
-
这是github上的代码
-
@Supersharp 哇,你是救生员!我花了 30 分钟四处搜索和几个小时试图解决这个问题,但我想我使用了错误的短语。非常感谢您的帮助!
标签: web-component shadow-dom custom-element html-imports html5-template