javascript - Web 组件模板错误

标签 javascript templates web components web-component

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

相关文章:

javascript - React-native- 如果数组为空,则有条件地禁用 TouchableHighlight

javascript - Zend 将服务器 url/参数传递给 javascript 文件

xml - 如何更改magento布局xml中<操作方法="addLinkBlock” …>的顺序?

php - 以 PHP 形式处理来自文本框和文件的输入

javascript - 光滑的旋转木马图像不会缩放

javascript - 如何在单个 Django View 中进行两个或多个 AJAX 调用

javascript - 在 Grunt 任务中运行命令

c++ - 如何检查类型是否提供具有算术类型的函数

javascript - 尝试导入错误 : 'GridActionsCellItem' is not exported from '@mui/x-data-grid'

Facebook 帐户取消链接或取消授权 Facebook 应用程序并检查 Facebook 应用程序的链接状态