1

我正在创建简单的自定义元素,我想从单独的文件中导入它。当它在同一个文件t中时,给出正确的 html 元素,但当它在外部文件中时,它是undefined. 这是我的index.html文件:

<!DOCTYPE html>  
<html lang="en">  
  <head>
    <meta charset="utf-8">
    <link rel="import" href="example-container.html">
  </head>
  <body>
    <example-container></example-container>
  </body>
</html>

并且example-container.html

<template id="example-container">
    <style>
    </style>
</template>
<script>  
    // Make sure you extend an existing HTMLElement prototype
    var ExampleContainerProto = Object.create(HTMLElement.prototype);

    //var t = document.querySelector('#example-container');

    // Setup optional lifecycle callbacks
    ExampleContainerProto.createdCallback = function() {
        var t = document.querySelector('#example-container');
        console.log(t);
    };
    var ExampleContainer = document.registerElement('example-container', {prototype: ExampleContainerProto});
</script>

我的另一种方法是t在全局范围内定义,如下所示:

var t = document.querySelector('#wizard-container');
WizardContainerProto.createdCallback = function() {
    console.log(t);
...

它工作得很好,但我不想在全局范围内留下垃圾。

4

1 回答 1

1

使用导入时,全局document对象引用父页面 (index.html),而不是导入的页面 (example-container.html)。您可以使用document.currentScript.ownerDocument. 因此,看起来您正在查询错误的文档。

请参阅HTML5Rocks 上的 HTML 导入 - #include for web

于 2015-06-11T20:49:11.723 回答