这是我的index.html 文件:
<!DOCTYPE html>
<html>
<head>
<script src="webcomponentsjs/webcomponents.js"></script>
<link rel="import" href="test-component.html">
</head>
<body>
<test-component id ="host">
<p>test</p>
</test-component>
</body>
</html>
这是 test-component.html 文件:
<template id = "template">
<p> this is the shadow dom</p>
<content select = "p"></content>
</template>
<script>
var test_component = document.registerElement("test-component", {
prototype: Object.create(HTMLElement.prototype,{
createdCallback:{
value: function(){
var host = document.querySelector("#host");
var root = host.createShadowRoot();
var template = document.querySelector("#template");
var content = document.importNode(template.content, true);
root.appendChild(content);
}
}
})
});
</script>
由于某种原因,我在这一行收到错误:
var content = document.importNode(template.content, true);
错误是:
Uncaught TypeError: Cannot read property 'content' of null
有人知道为什么会发生这种情况吗?
最佳答案
在test-component.html
中尝试这种方式获取模板
var template = document.currentScript.ownerDocument.querySelector("#template");
关于javascript - Web 组件模板错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31448723/