普通 JavaScript 中的 Web 组件

问题描述 投票:0回答:3
web-component custom-element
3个回答
1
投票

您的内联脚本在导入clock.js之前运行

(这是异步的,因为您已将 
async
 属性添加到 
<script>
 标记)。由于该元素是在 
clock.js
 中定义的,因此当您的内联脚本尝试访问它们时,
<clock-digital>.method
<clock-digital>.cID
 还不存在。

几个选项:


1
投票
为了保持脚本异步 (

async

)(有时效果更好),您可以向 
onload
 元素添加一个 
<script>
 事件处理程序,该处理程序将调用您的内联脚本:

<script> function init() { console.log(document.querySelector('clock-digital').cID); document.querySelector('clock-digital').method(); } </script> <script src="clock.js" async onload="init()"></script>
    

0
投票
WebComponents API 已经为您介绍过了。只需在此处使用

customElements.whenDefined(tagName)

 承诺即可:

customElements.whenDefined('clock-digital').then(() => { console.log(document.querySelector('clock-digital').cID); document.querySelector('clock-digital').method(); });
    
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.