【问题标题】:Webcomponents v1 - Illegal constructorWebcomponents v1 - 非法构造函数
【发布时间】:2023-03-28 05:25:02
【问题描述】:

尝试使用 webcomponents,但遇到了一个我没有得到的错误。

标记很简单,应该可以工作。 2个文件,都是html文件。

错误标记在控制台的<script> 标记上。

感谢您的帮助。

PS。我正在运行 Google Chrome Beta 以使 customElements 工作。

km-button.html

<script>

class KmButton extends HTMLButtonElement {

   constructor() {
     super();
   }

}

customElements.define('km-button', KmButton, {extends: 'button'});

</script>

index.html

<!DOCTYPE html>
<html>
    <head>
        <!--  import webcomponents  -->
        <link rel="import" href="./components/km-button.html">
    </head>
    <body>
        <km-button>hej</km-button>
    </body>
</html>

错误

km-button.html:1 Uncaught TypeError: Illegal constructor(…)KmButton @ km-button.html:7

【问题讨论】:

    标签: javascript html web-component custom-element


    【解决方案1】:

    实际上它仍然不起作用(在您更正之后)。

    AFAIK extends 功能尚未在 Chrome 的自定义元素 v1 中实现。

    因此is= 语法被简单地(并且默默地)忽略,您的按钮被视为标准&lt;button&gt;

    【讨论】:

    • hmm ok 只是认为它可以工作,因为它不再给出错误,最终没有使用 is= 语法,因为 Apple 似乎不会在 Webkit 中实现它。不过谢谢你告诉我。
    • 一种解决方法是使用这个 polyfill:github.com/WebReflection/document-register-element
    • 感谢您的链接,但我不认为在开发过程中添加 polyfill 是一个好习惯,并且它们只应在“结束”为最终用户执行构建任务时使用"。
    • 如果你这么说:) 不知道如何回复。但这不是争论的地方,所以我就顺其自然吧。
    • 我的意思是使用 this 库来开发自定义元素 (v1) 并预测其未来的浏览器实现并不是一个坏习惯。
    【解决方案2】:

    是的,当您扩展另一个 DOM 元素时,我似乎误认为 &lt;km-button&gt;&lt;/km-button&gt; 标签应该是 &lt;button is="km-button"&gt;some text&lt;/button&gt;

    如果有人遇到同样的错误,请留下问题。

    【讨论】:

      猜你喜欢
      • 2015-06-28
      • 2010-10-30
      • 1970-01-01
      • 2023-03-20
      • 2021-11-24
      • 1970-01-01
      • 2010-12-11
      • 2013-12-13
      • 1970-01-01
      相关资源
      最近更新 更多