簡體   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