2017-08-18 88 views
1

我試圖創建一個自定義的錶行,但有困難得到它正確的行爲。我已經嘗試了以下兩種方法,他們給出了奇怪的結果。我意識到,如果沒有自定義元素,這很容易,但這是一個更大項目的小例子。我可以改變什麼來達到預期的效果?創建自定義錶行

class customTableRow extends HTMLElement { 
 
    constructor(){ 
 
    super(); 
 
    
 
    var shadow = this.attachShadow({mode: 'open'}); 
 
    
 
    this.tableRow = document.createElement('tr'); 
 
    
 

 
    var td = document.createElement('td'); 
 
    td.innerText = "RowTitle"; 
 
    this.tableRow.appendChild(td); 
 
    
 
    var td2 = document.createElement('td'); 
 
    td2.innerText = "RowContent"; 
 
    td2.colSpan = 4; 
 
    this.tableRow.appendChild(td2); 
 

 
    shadow.appendChild(this.tableRow); 
 
    } 
 
    
 
} 
 

 
customElements.define('custom-tr', customTableRow); 
 

 
//Attempt 2 
 
var newTr = new customTableRow; 
 
document.getElementById('table2Body').appendChild(newTr);
td { 
 
    border: 1px solid black; 
 
}
<span>Attempt 1:</span> 
 
<table> 
 
    
 
    <thead> 
 
    <tr> 
 
     <th>One</th> 
 
     <th>Two</th> 
 
     <th>Three</th> 
 
     <th>Four</th> 
 
     <th>Five</th> 
 
    </tr> 
 
    </thead> 
 
    
 
    <tbody> 
 
    <custom-tr /> 
 
    </tbody> 
 
    
 
</table> 
 

 
<hr> 
 

 
<span>Attempt 2:</span> 
 
<table id="table2"> 
 

 
    <thead> 
 
    <tr> 
 
     <th>One</th> 
 
     <th>Two</th> 
 
     <th>Three</th> 
 
     <th>Four</th> 
 
     <th>Five</th> 
 
    </tr> 
 
    </thead> 
 
    
 
    <tbody id="table2Body"> 
 
<!--  It should append here --> 
 
    </tbody> 
 
    
 
</table> 
 

 
<hr> 
 

 
<span>This is how I want it to look:</span> 
 
<table id="table2"> 
 

 
    <thead> 
 
    <tr> 
 
     <th>One</th> 
 
     <th>Two</th> 
 
     <th>Three</th> 
 
     <th>Four</th> 
 
     <th>Five</th> 
 
    </tr> 
 
    </thead> 
 
    
 
    <tbody> 
 
    <tr> 
 
     <td>Row Title</td> 
 
     <td colspan="4">Row Content</td> 
 
    </tbody> 
 
    
 
</table>

回答

2

<table>元件及其子組件<tbody><tr>需要一個非常具體的語法。例如,只有<tr>元素被授權爲<tbody>的子元素。

因此你不能定義一個元素和<tbody><table>插入。如果你這樣做,它將在解析時被移動<table>。因此顯示你的第一個例子(查看開發工具中的代碼)。

相反,您應該定義一個自定義標記而不是像this answer to a similar question

或者你應該用<custom-table>,<custom-tbody> ......像this other answer那樣重新定義一個完整的自定義表結構。

此外,你應該使用關閉標籤<custom-tr></custom-tr>,如果你想讓它通過其內部應用插入影子DOM的CSS規則。

+0

嗯,我將不得不對此事的看法,並做一些更多的閱讀。我對web dev相當陌生,這可能比我可以咀嚼的東西更大。如果可能的話,通過擴展一個'tr'類來創建一個新類會更容易嗎? – h01001000

+0

這個怎麼做?回顧一下,我似乎可以擴展'HTMLTableRowElement',但我一直沒有找到一種方法來編寫這個沒有拋出'Illegal Constructor'錯誤。 – h01001000

+1

作爲一個例子,溶液2的[此答案](https://stackoverflow.com/a/43086994/4600982)定義V1與填充工具 – Supersharp