小编h01*_*000的帖子

创建自定义表格行

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

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);
Run Code Online (Sandbox Code Playgroud)
td {
  border: 1px solid black;
}
Run Code Online (Sandbox Code Playgroud)
<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> …
Run Code Online (Sandbox Code Playgroud)

html javascript web-component shadow-dom custom-element

2
推荐指数
1
解决办法
2401
查看次数