【问题标题】:Can I define two custom html elements with customElements.define?我可以使用 customElements.define 定义两个自定义 html 元素吗?
【发布时间】:2021-05-14 05:33:16
【问题描述】:

我编写了一个扩展 HTMLElement 的类,并准备使用 customElements.define 将元素绑定到 Dom。我认为可以根据需要创建尽可能多的元素,但不知何故并非如此。

    let but = factory.createButtonElement('./img/question2.png');
    let butt = factory.createButtonElementt('./img/question2.png');
    customElements.define('sel-but', but);
    customElements.define('sel-butt', butt);
    /**
     * Also tried this
     * customElements.whenDefined('sel-but').then(()=>{
     *  customElements.define('sel-butt', butt);
     * })
     */

而我的 HTML 外观有这两个元素

    <sel-but></sel-but>
    <sel-butt></sel-butt>

错误

Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': this constructor has already been used with this registry

如何在屏幕上显示两个按钮?

谢谢

【问题讨论】:

  • 你能把它变成一个工作的 SO sn-p: [ ] 在编辑工具栏上,包括你的工厂函数

标签: javascript html custom-element native-web-component


【解决方案1】:

两个工厂方法都指向同一个类。而且因为 CustomElementRegistry 只能保存一个构造函数,所以它会返回错误。

【讨论】:

    【解决方案2】:

    Make it 2 定义,即扩展

    class ButElement extends HTMLElement {
         ...
    }
    
    customElements.define("sel-but", class extends ButElement{});
    customElements.define("sel-butt", class extends ButElement{});
    
    
    // I don't know your factory functions... something like this:
    let klass = factory.createButtonElement('./img/question2.png');
    customElements.define("sel-but", class extends klass );
    customElements.define("sel-butt", class extends klass );
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 2015-12-04
      • 2017-07-08
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 2019-12-11
      • 1970-01-01
      相关资源
      最近更新 更多