繁体   English   中英

导入文件中的ID找不到模板

[英]Can't find template by id when it's in imported file

我正在创建简单的自定义元素,我想将其从单独的文件中导入。 当它在同一个文件中时, 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);
...

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

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

有关HTML5Rocks上的网络信息 ,请参见HTML导入-#include

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM