如何从链接的 javascript 文件中访问自定义元素? [英] How to access custom element from within a linked javascript file?

查看:33
本文介绍了如何从链接的 javascript 文件中访问自定义元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的剧本

<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 等效的自定义元素?

From within main.js how can I access the custom element which is equivalent to this in the constructor()?

谢谢

推荐答案

您不能按照 此线程:currentScript 属性将返回 null.

You cannot do that as explained in this thread: The currentScript property will return null.

相反,您应该在