簡體   English   中英

嘗試在 html 導入中選擇模板元素時獲取空值

[英]Getting null when trying to select a template element in an html import

在我的應用程序中,我將 html 從A導入到具有此文件的文件B 但它警告為空。 如果我直接在瀏覽器中打開B ,它會提醒模板 HTML dom 元素。 這怎么會發生,同樣的代碼幾乎來自谷歌自己的網絡組件文檔https://developers.google.com/web/fundamentals/architecture/building-components/customelements

<template id="x-foo-from-template">

</template>

<script>
    alert(document.querySelector('template'));
</script>

這是谷歌的例子:

<template id="x-foo-from-template">
  <style>
    p { color: orange; }
  </style>
  <p>I'm in Shadow DOM. My markup was stamped from a &lt;template&gt;.</p>
</template>

<script>
  customElements.define('x-foo-from-template', class extends HTMLElement {
    constructor() {
      super(); // always call super() first in the ctor.
      let shadowRoot = this.attachShadow({mode: 'open'});
      const t = document.querySelector('#x-foo-from-template');
      const instance = t.content.cloneNode(true);
      shadowRoot.appendChild(instance);
    }
    ...
  });
</script>

謝謝

為什么會發生這種情況?

導入包含scripttemplate的文件時要考慮的兩個因素:

  1. script將在導入時執行,而標記和其他資源需要顯式添加到主頁

導入鏈接並不意味着“ #include the content here ”。 它的意思是“解析器,去獲取這個文檔,以便我以后可以使用它”。 雖然腳本在導入時執行,但樣式表、標記和其他資源需要明確添加到主頁中。

  1. 導入中的腳本在包含導入文檔的窗口上下文中執行。 所以window.document指的是主頁面文檔,而不是模板文檔。

這應該可以解釋為什么您的腳本會警告null 因為腳本是立即執行的,而模板尚未添加到主頁中。

如何得到想要的結果:

您可以創建對導入文檔本身的引用,其中可以找到template

// importDoc references this import's document
var importDoc = document.currentScript.ownerDocument;

alert(importDoc.querySelector('template'));

或者,您可以在將模板插入文檔后查詢主文檔:

var import = document.querySelector('link[rel="import"]').import;
var template = import.querySelector('template');

// Append template to main document
document.head.appendChild(template);

// Now you can query the main the document
alert(document.querySelector('template'));

Google 的示例與相關示例有何不同?

回答以下評論中的問題:

在 Google 的示例中,在自定義元素的構造函數中可以找到對document.querySelector()的調用。 構造函數在元素被實例化時被調用。 因此,當運行此代碼時,該元素已存在於主頁中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM