哈士奇WWW
2021-11-18 09:55:35
我試圖使用 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 語法中缺少什么嗎?
1 回答

慕沐林林
TA貢獻2016條經驗 獲得超9個贊
它不工作,因為你打電話customElements.define-and從而升級<neo-element>到的實例NeoElement,之前你已經定義NeoElement.prototype,NeoElement.prototype.constructor和NeoElement.prototype.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>
添加回答
舉報
0/150
提交
取消