[英]How do I create the TBody tag in a Table with pure JavaScript?
如何使用纯 JavaScript 在 Table 标签内创建 TBody 标签? (不可手动篡改 HTML 码)。 有HTMLTableElement.createTHead()
和HTMLTableElement.createTFoot()
函数,但没有关于 TBody 元素的函数。 此外,一旦您创建了 THead 元素,使用HTMLTableElement.insertRow()
添加到表中的以下所有行都会添加到 THead 元素。
那么 go 如何在不手动篡改 HTML 的情况下在 THead 下创建一个 TBody 元素?
接口HTMLTableElement
表上的创建和删除方法允许作者构建和修改表。 HTML 4.0 指定 CAPTION、THEAD 和 TFOOT 元素中的每一个只能存在于一个表中。 因此,如果存在并调用 createTHead() 或 createTFoot() 方法,则该方法返回现有的 THead 或 TFoot 元素。
所以 createTHead 和 createTFoot 是不一定进行实际创建的便捷方法。
相比之下,表格元素可以有任意多个<tbody>
,因此不需要特殊的方法, HTMLTableElement.appendChild(document.createElement('tbody'))
将完成完整的工作。
更新:在撰写此答案时,为了完整性,已经将createTBody()
添加到当时的 HTML5 草案标准中,但没有实现,也不知道是否会有。 事实上,Webkit 是 2012 年实现的,Gecko 是 2013 年实现的。
创建 THead 元素后,使用 HTMLTableElement.insertRow() 添加到表中的以下所有行都将添加到 THead 元素。
我偶然发现了相同的行为,也找不到名为HTMLTableElement.createTBody()
的 function(它不存在)。
但我发现insertRow()
(或其他函数之一)似乎包含表 state 逻辑,因为它将自动创建<tbody>
- 除非<thead>
已经创建。
所以解决方案是(在 Windows 10 上使用 Firefox 62.0.2(64 位))先创建表体,然后创建 header:
var tbl = document.createElement('table'); // tbody var tr = tbl.insertRow(); var tc = tr.insertCell(); var tt = document.createTextNode("tbody"); tc.appendChild(tt); // thead var th = tbl.createTHead(); var thr = th.insertRow(); if (true) { // works var thc = document.createElement('th'); thr.appendChild(thc); } else { // does not work var thc = thr.insertCell(); } var tht = document.createTextNode("thead"); thc.appendChild(tht); // tfoot var tf = tbl.createTFoot(); var tfr = tf.insertRow(); var tfc = tfr.insertCell(); var tft = document.createTextNode("tfoot"); tfc.appendChild(tft); // document.getElementById('target').appendChild(tbl);
body { background-color: #eee; } table { border: 2px solid white; } thead { background-color: red; } tbody { background-color: green; } tfoot { background-color: blue; } th { border: 2px solid green; } tr { /*background-color: #eee;*/ } td { border: 2px solid black; }
<div id="target"></div>
文档:
HTML
JavaScript
createTBody()
似乎还没有记录在案,但它至少在今天已经存在并且按预期工作:
let table = document.createElement('table'); console.log('empty table: ', table.outerHTML); table.createTBody(); console.log('table with tbody: ', table.outerHTML);
预计 output:
empty table: <table></table>
table with tbody: <table><tbody></tbody></table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.