在我的应用程序中,我将 A
的 html 导入到包含此文件的 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 <template>.</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>
谢谢
最佳答案
为什么会这样?
导入包含脚本
和模板
的文件时要考虑的两个因素:
脚本
将在导入时执行,而标记和其他资源需要显式添加到主页- 正如本 article on imports 中所指出的(Eric Bidelman,与相关 Google 文档的作者相同):
An import link doesn't mean "#include the content here". It means "parser, go off an fetch this document so I can use it later". While scripts execute at import time, stylesheets, markup, and other resources need to be added to the main page explicitly.
- 导入中的脚本在包含导入文档的窗口的上下文中执行。所以
window.document
指的是主页面文档,不是模板文档。
这应该可以解释为什么您的脚本会提示 null
。因为脚本是立即执行的,而模板还没有添加到主页面。
如何得到想要的结果:
您可以在可以找到模板
的地方创建对导入文档本身的引用。
// 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()
的调用。实例化元素时调用构造函数。因此,运行此代码时该元素已存在于主页面中。
关于javascript - 尝试在 html 导入中选择模板元素时获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45726483/