【问题标题】:How to access custom element from within a linked javascript file?如何从链接的 javascript 文件中访问自定义元素?
【发布时间】:2017-08-19 14:25:41
【问题描述】:

如果我有这样的脚本

<template id="x-foo-from-template">
    <script src="/js/main.js"></script>
</template>

<script>
    customElements.define('my-header', class extends HTMLElement {
        constructor() {
            super();
            let shadowRoot = this.attachShadow({mode: 'open'});
            const t = document.currentScript.ownerDocument.querySelector('#x-foo-from-template');
            const instance = t.content.cloneNode(true);
            shadowRoot.appendChild(instance);

            // set up title
            var title = this.getAttribute("title");
            var div = document.createElement("div");
            div.innerText = title;
            shadowRoot.appendChild(div);
        }
    });
</script>

如何从main.js 中访问与constructor() 中的this 等效的自定义元素?

谢谢

【问题讨论】:

    标签: javascript web-component custom-element html5-template


    【解决方案1】:

    您不能按照this thread 中的说明执行此操作:currentScript 属性将返回 null

    相反,您应该在&lt;template&gt; 之外加载脚本,并从您的自定义元素回调connectedCallback()constructor() 调用脚本中定义的函数。

    【讨论】:

      【解决方案2】:

      您必须在组件外部访问currentScript。我用这个:

      var frag = (document.currentScript||document._currentScript).ownerDocument.querySelector('template').content;
      

      我使用 (document.currentScript||document._currentScript) 来处理 polyfill。

      然后在你的构造函数中你会使用:

      const instance = frag.cloneNode(true);
      

      此时fragdocument-fragment 并且可以包含任意数量的子代。所有这些都将通过对cloneNode 的调用进行复制,以便您的 Web 组件的每个实例都有自己的 DOM 副本。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-23
        • 1970-01-01
        • 1970-01-01
        • 2013-11-27
        • 2021-03-26
        • 1970-01-01
        • 1970-01-01
        • 2021-04-18
        相关资源
        最近更新 更多