为什么在一切正常时 importNode 不执行?

Why isn't importNode executing when everything is fine?

我想使用 HTML 导入,所以我创建了两个文件。
文件 1:

<!DOCTYPE html>
<html>
<head>
    <style>
        div {
            height: 300px;
            width: 300px;
            background-color: yellow;
        }
    </style>
</head>
<body>
    <div></div>
</body>
</html>

文件 2:

<!DOCTYPE html>
<html>
<head>
    <link rel='import' href='test.html' id='LINK'>
    <script>
        var LINK = document.getElementById('LINK');
        var test = LINK.import;
        var content = document.importNode(test.content, true);
        document.body.appendChild(content);

    </script>
</head>
<body>        
</body>
</html>

我在执行 File2 时应该会看到一个黄色方块,但我却收到了这个错误:

Uncaught TypeError: Failed to execute 'importNode' on 'Document': parameter 1 is not of type 'Node'. at Import.html:8

当我将 "test" 变量记录到控制台时,我得到了包含 File1 的文档,所以在那里没问题。我只是不明白错误的含义以及为什么它不起作用。

当你写:

var content = document.importNode(test.content, true);

...您假设 test 是一个 <template> 元素。

因此在您导入的文档中,您应该有一个 <template> 元素。

test.html:

<html>
<head>
    <style>
        div {
            height: 300px;
            width: 300px;
            background-color: yellow;
        }
    </style>
</head>
<body>
    <template><div></div></template>
</body>
</html>

在主文件中,使用querySelector()(或其他选择器函数)获取模板:

var LINK = document.getElementById('LINK');
var test = LINK.import.querySelector('template');
var content = document.importNode(test.content, true);
...