gpt4 book ai didi

javascript - 如何从链接的 javascript 文件中访问自定义元素?

转载 作者:行者123 更新时间:2023-11-30 21:15:02 26 4
gpt4 key购买 nike

如果我有这样的脚本

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

谢谢

最佳答案

您不能按照 this thread 中的说明那样做: currentScript属性(property)将返回null .

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

关于javascript - 如何从链接的 javascript 文件中访问自定义元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45772685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com