创建自定义html元素时未调用连接的回调

问题描述 投票:0回答:1

我正在尝试使用JavaScript在HTML中创建自定义标签。我想使用ES6 JavaScript语法创建自定义元素。我已经编写了这段代码来创建自定义元素:

customElements.define('neo-element', NeoElement);
function NeoElement (){
    var ref =  Reflect.construct(HTMLElement,[], this.constructor) ;
    return ref;
};
NeoElement.prototype = Object.create(HTMLElement.prototype);
NeoElement.prototype.constructor = NeoElement;
NeoElement.prototype.connectedCallback = function(){
    this.innerHTML = `<h1>Hello world</h1>`;
};
<neo-element></neo-element>

我已经验证NeoElement正确地扩展了HTMLElement,但是<neo-element>标签内部仍然没有打印任何内容。

有人可以看一下代码,然后告诉我我在ES5语法中缺少什么吗?

javascript html css ecmascript-6 ecmascript-5
1个回答
0
投票

这不起作用,因为您在定义customElements.define之前就调用了connectedCallback。如果将customElements.define移到末尾,它将正常工作:

function NeoElement() {
    var ref = Reflect.construct(HTMLElement,[], this.constructor) ;
    return ref;
};
NeoElement.prototype = Object.create(HTMLElement.prototype);
NeoElement.prototype.constructor = NeoElement;
NeoElement.prototype.connectedCallback = function(){
    this.innerHTML = `<h1>Hello world</h1>`;
};
customElements.define('neo-element', NeoElement);
<neo-element></neo-element>
© www.soinside.com 2019 - 2024. All rights reserved.