gpt4 book ai didi

javascript - Web 组件模板错误

转载 作者:行者123 更新时间:2023-11-30 08:35:54 25 4
gpt4 key购买 nike

这是我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com