创建自定义 table 行

Creating a custom table row

我正在尝试创建一个自定义 table 行,但很难使其正常运行。我已经尝试了以下两种方法,但它们给出了奇怪的结果。我意识到如果没有自定义元素,这很容易做到,但这是一个更大项目的小例子。我可以改变什么来达到预期的结果?

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>

<table> 元素及其子组件 <tbody><tr> 需要非常具体的语法。例如,只有 <tr> 个元素被授权为 <tbody> 的子元素。

因此您不能定义元素并将其插入 <tbody><table>。如果你这样做,它将在解析时被移到 <table> 之外。因此显示了您的第一个示例(查看开发工具中的代码)。

您应该定义一个 自定义标签 而不是像 .

或者您应该使用 <custom-table><custom-tbody>...重新定义一个完整的自定义 table 结构,如 .

此外,您应该使用结束标记 <custom-tr></custom-tr>,并在影子 DOM 中插入您的 CSS 规则(如果您希望在其中应用它)。