javascript - 创建自定义表格行

标签 javascript html web-component shadow-dom custom-element

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

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> 之外在解析时。因此显示了您的第一个示例(查看开发工具中的代码)。

相反,您应该定义一个自定义标签,如this answer to a similar question .

或者您应该使用 <custom-table> 重新定义完整的自定义表结构, <custom-tbody> ...就像 this other answer .

此外,您应该使用结束标签 <custom-tr></custom-tr> ,如果您希望在 Shadow DOM 中应用 CSS 规则,请将其插入到 Shadow DOM 中。

关于javascript - 创建自定义表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45764553/

相关文章:

javascript - 如何比较两个对象数组并获取共同对象

javascript - AngularJs 乘以 100 时给出错误的结果

javascript - 不要包含使用 node-tar 进行存档的绝对路径

html - 如果动态内容需要更多空间,是否可以隐藏 html 元素?

security - Shadow DOM 是否能够保护元素?

javascript - 创建和使用自定义 HTML 组件?

javascript - 当用户向下滚动我的网页时,如何删除 chrome 地址栏周围的边框

javascript - 如何使用 Angularjs 在 Internet Explorer 中上传文件后清除文件名

html - AngularDart 文本区域安全 HTML 字符串编辑器

html - 隔离 WebComponent JS 库