javascript - 读取嵌套模板的内容

标签 javascript html polymer web-component

如何让 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/

相关文章:

javascript - 在 Javascript 函数中编写 PHP

javascript - 根据数组值打乱字符串 - Javascript

javascript - 对象属性在 Javascript 上返回 'undefined'

html - div中的Struts2标签显示为空

javascript - jQuery 自动完成 - 未捕获的类型错误 : undefined is not a function

jQuery 从 div 中删除 contains() 文本

html - 具有 contentEditable(html 编辑)的 UIWebView,第一响应者处理?

polymer - 未捕获的 ReferenceError : Polymer is not defined after event. preventDefault()

polymer 1.x : How to use Polyfills to shim support for CSS variables

javascript - 由于影子元素,查询 polymer 3 中页面中的所有元素(queryselectorall)不起作用