2017-02-23 42 views
2

我試圖定義新的自定義元素。如何爲同一類定義更多自定義元素

// the class 
 
class MyEl extends HTMLElement { 
 
    constructor() { 
 
    // mandatory super call to upgrade the current context 
 
    super(); 
 
    // any other Class/DOM related procedure 
 
    this.setAttribute('custom-attribute', 'value'); 
 
this.innerText = 'new element'; 
 
    } 
 
} 
 

 
// its mandatory definition 
 
customElements.define('my-el', MyEl); 
 

 
// the JS way to create a custom element 
 
const newMe = new MyEl(); 
 

 

 
document.body.appendChild(newMe);

定義相同類的新元素將導致錯誤:
「未捕獲拋出:DOMException:未能執行‘規定’關於‘CustomElementRegistry’:
此構造已經被使用此註冊表「

但我想爲同一類定義新的元素。 你能否建議一種方法來顯示來自同一類(MyEl)的多個項目。
預先感謝!

回答

1

customElements.define('my-el', MyEl)必須只被調用一次告訴瀏覽器您有一個新的<my-el>標籤(又名定義自定義元素)。

然後你可以只需使用new創建多個元素:

const newMe1 = new MyEl(); 
const newMe2 = new MyEl(); 

或者createElement()

const newMe1 = document.createElement('my-el') 
const newMe2 = document.createElement('my-el') 

或者,在html代碼:

<my-el></my-el> 
<my-el></my-el> 
相關問題