关于jquery:如果不明确使用thead和tbody,为什么浏览器不查找第一个”内容行”来添加” tbody”?

Why don't browsers look for the first “content row” to add “tbody” if you don't use thead and tbody explicitly?

当我查看W3schoool时,初始教程或示例不使用thead或tbody,但是我有如下所示的jQuery代码:

1
$("#mytable tbody tr:nth-child(odd)").addClass("oddColor");

1
$("#mytable tr:nth-child(odd)").addClass("oddColor");

我的桌子看起来像这样(注意没有thead或tbody标签)

1
2
3
4
5
6
7
8
<table>
  <tr><th>Col1</th><th>Col2</th></tr>

  <tr><td>Row 1</td><td>Row 1</td></tr>
  <tr><td>Row 2</td><td>Row 2</td></tr>
  <tr><td>Row 3</td><td>Row 3</td></tr>
  <tr><td>Row 4</td><td>Row 4</td></tr>
</table>

jQuery是否将" th"行计为tbody?如果浏览器自动将tbody添加到tbody中,为什么不将其放在" td"行(而不是" th"行)中
看起来确实如此,但是我会以为它会寻找第一个" td"行。

很明显,通过在所有表上添加thead和tbody使其100%显式,但是当这些标签不存在时jQuery会做什么以及它为什么会那样表现,这让我感到困惑。

也许更好的问题是,如果浏览器添加tbody,为什么不将tbody添加到td行而不是th行呢?


tbody是自动创建的,并且如果未显式使用tbodythead,则将package所有表行。正文行中允许使用th,而这些行的内容没有"检查"即可查看哪些行应为标题行或正文行。

如果您要使用thead,且行已从tbody中排除,则必须显式添加-在这一点上,您还需要添加tbody

请参阅为什么浏览器将tbody元素插入表元素?


Dave Raggett从1996年开始在RFC1942(HTML表格)中说

Tables may be divided up into head and body sections. The THEAD and TFOOT elements are optional, but one or more TBODY elements are always required. If the table only consists of a TBODY section, the TBODY start and end tags may be omitted, as the parser can infer them. If a THEAD element is present, the THEAD start tag is required, but the end tag can be omitted, provided a TFOOT or TBODY start tag follows. The same applies to TFOOT.

Note: This definition provides compatibility with tables created for the older model, as well as allowing the end tags for THEAD, TFOOT and TBODY to be omitted. (my emphasis)

The THEAD, TFOOT and TBODY elements provide a convenient means for controlling rendering. If the table has a large number of rows in the body, user agents may choose to use a scrolling region for the table body sections. When rendering to a paged device, tables will often have to be broken across page boundaries. The THEAD, TFOOT and TBODY elements allow the user agent to repeat the table foot at the bottom of the current page, and then the table head at the top of the new page before continuing on with the table body.

"较旧的模型"出现在HTML 3.0中。尽管HTML 3.0在完成之前就被HTML 3.2取代而被放弃了,但似乎至少有一些表是在此期间创建的。它说:

Content Model: Optional CAPTION, then one or more table rows (TR)

即那时没有TBODY,THEAD或TFOOT元素。

因此,假设当时创建的那些表将期望所有行,无论它们包含TH元素还是TD元素都具有类似TBODY的行为,例如该行不会像分别在THEAD和TFOOT中预期的那样在每个打印页面的顶部和底部重复。

因此,为了向后兼容,仅使用TBODY进行package与HTML表的原始用法是一致的。