0

我编写了一个扩展 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

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

谢谢

4

2 回答 2

0

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

于 2021-02-11T07:11:13.457 回答
0

使其 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 );

于 2021-02-11T11:33:27.417 回答