【问题标题】:Web components in vanilla JavaScript原生 JavaScript 中的 Web 组件
【发布时间】:2017-05-12 16:24:53
【问题描述】:

我创建了一个没有任何框架的小型 Web 组件。这是我的index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <title></title>
    <meta charset="UTF-8">
    <script src="clock.js" async></script>
</head>

<body>
    <clock-digital></clock-digital>
    <script>
        console.log(document.querySelector('clock-digital').cID);
        document.querySelector('clock-digital').method();
    </script>
</body>

</html>

这是我的clock.js

customElements.define('clock-digital', class extends HTMLElement {

    get cID() {}

    set cID(value) {}

    constructor() {
        super();
        var shadowRoot = this.attachShadow({
            mode: 'open'
        });
        var that = shadowRoot;
        this.cID = setInterval(function () {
            var currentdate = new Date();
            that.innerHTML = `<div style="display: inline; background-color: whitesmoke; font-style: italic;">${currentdate.getHours()}:${currentdate.getMinutes()}:${currentdate.getSeconds()}</div>`;
        }, 500);
    }

    method() {
        console.log('method');
    }

});

浏览器控制台显示此错误:

undefined

(index):14 Uncaught TypeError: document.querySelector(...).method is not a function
at (index):14

为什么我的内联脚本无法访问cIDmethod()

【问题讨论】:

  • 如果您将选择分配给一个变量然后调用它的方法,它仍然会发生吗?类似var clock = document.querySelector('clock-digital'); clock.method();
  • 谢谢我也必须删除异步

标签: web-component custom-element


【解决方案1】:

您的内联脚本运行之前 clock.js 被导入(这是异步的,因为您已将async 属性添加到&lt;script&gt; 标记中)。由于该元素是在 clock.js 中定义的,所以当您的内联脚本尝试访问它们时,&lt;clock-digital&gt;.method&lt;clock-digital&gt;.cID 还不存在。

几个选项:

  • 删除 async 标记,以便在您的内联脚本运行之前同步导入 (demo)。您将失去异步加载的优势,但这对您来说可能不是问题。
  • 超时后运行您的内联脚本(允许clock.js 完成导入)

【讨论】:

  • 如果我删除异步并且如果我写 var clock = document.querySelector('clock-digital');时钟.method();
  • async 标签是您的根本问题。在demo 中,您可以看到只有删除async 才能让您的原始代码按预期工作。不缓存 clock 不是问题。
【解决方案2】:

为了使脚本保持异步 (async),这有时会更好,您可以将 onload 事件处理程序添加到 &lt;script&gt; 元素,这将调用您的内联脚本:

<script>
  function init() {
      console.log(document.querySelector('clock-digital').cID);
      document.querySelector('clock-digital').method();  
  }
</script>

<script src="clock.js" async onload="init()"></script>

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    相关资源
    最近更新 更多