如何让 JS 访问 .content
嵌套 <template>
?
我正在尝试扩展 <template>
和我的 imported-template
元素(从外部文件获取模板内容),我想实现 <imported-content>
以类似于 native 的方式<content>
.为此,我只是尝试
this.content.querySelector("imported-content")
但它发生了,对于嵌套模板this.content
是空的。
<script>
(function() {
var XHTMLPrototype = Object.create((HTMLTemplateElement || HTMLElement).prototype);
XHTMLPrototype.attachedCallback = function() {
//..
var distributeHere = this.content.querySelector("imported-content");
var importedContent = document.createElement("span");
importedContent.innerHTML = "Imported content";
distributeHere.parentNode.replaceChild(importedContent, distributeHere);
}
document.register('imported-template', {
prototype: XHTMLPrototype,
extends: "template"
});
})();
</script>
<template id="fails" bind>
<ul>
<template is="imported-template" bind="{{ appdata }}">
<li>
<imported-content></imported-content>
</li>
</template>
</ul>
</template>
JSFiddle here
我不确定这是错误、设计问题还是模板 shim 限制。
我想也许我在错误的生命周期回调中检查了它,所以我尝试了 MutationObserver
fiddle here , 但也不会发生突变。
最佳答案
我changed您的选择器到 this.content.querySelector("[is='imported-content']")
。这是你想做的吗?
关于javascript - 读取嵌套模板的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23643676/