简体   繁体   English

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

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

I'm creating simple custom element and i would like to import it from separated file. 我正在创建简单的自定义元素,我想将其从单独的文件中导入。 When it's in the same file t is giving right html element, but when it's in outside file it's undefined . 当它在同一个文件中时, t给出正确的html元素,但是当它在外部文件中时,它是undefined Here is my index.html file: 这是我的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>

And example-container.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>

My another approach was to define t in the global scope, like this: 我的另一种方法是在全局范围内定义t ,如下所示:

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

And it work's fine, but i don't want to leave garbage in the global scope. 它的工作很好,但我不想在全球范围内留下垃圾。

When using imports, the global document object refers to the parent page (index.html), not the imported page (example-container.html). 使用导入时,全局document对象引用父页面(index.html),而不引用导入页面(example-container.html)。 You can get the imported document using document.currentScript.ownerDocument . 您可以使用document.currentScript.ownerDocument获取导入的document.currentScript.ownerDocument So, it looks like you're querying the wrong document. 因此,看来您正在查询错误的文档。

See HTML Imports - #include for the web on HTML5Rocks. 有关HTML5Rocks上的网络信息 ,请参见HTML导入-#include

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

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