我正在尝试使用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语法中缺少什么吗?
这不起作用,因为您在定义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>