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