h01*_*000 2 html javascript 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);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>
<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>Run Code Online (Sandbox Code Playgroud)
一个<table>元素及其子组件<tbody>,<tr>需要一个非常特殊的语法。例如,只有<tr>元素被授权为 的子元素<tbody>。
因此,您不能定义一个元素并将其插入到<tbody>or 中<table>。如果你这样做,它将被移到<table>at 解析之外。因此显示了您的第一个示例(查看开发工具中的代码)。
相反,您应该像在对类似问题的回答中那样定义一个自定义标签。
或者您应该使用<custom-table>, <custom-tbody>...重新定义一个完整的自定义表结构,就像在另一个答案中一样。
此外,您应该使用结束标记<custom-tr></custom-tr>,并在 Shadow DOM 中插入您的 CSS 规则(如果您希望将其应用于其中的话)。
| 归档时间: |
|
| 查看次数: |
2401 次 |
| 最近记录: |