2017-07-08 35 views
1

我想使用HTML进口,所以我创建了两个文件。
文件1:为什么importNode在一切正常的时候不会执行?

<!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> 

我看到一个黄色的方形当我执行文件2,而是我得到这个错误:

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

当我将“test”变量记录到控制台,我得到包含File1的文档,因此在那里没问题。我只是不明白错误应该是什么意思,为什么它不起作用。

+0

您正在使用'import'不正确。您应该导入网页的“片段”,而不是整个网页。 –

+0

@ScottMarcus那么我该怎么做?我从我挖出的教程中使用这段代码。 – CodeMaker

回答

2

当你写:

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); 
... 
相关问题