如何从表格单元格(td)中获取相应的表格标题(th)?
给定下表,我如何获取每个 td 元素对应的表头?
<table>
<thead>
<tr>
<th id="name">Name</th>
<th id="address">Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>1 High Street</td>
</tr>
</tbody>
</table>
鉴于我目前已经拥有任何可用的 td
元素,我如何才能找到相应的 th
元素?
var $td = IveGotThisCovered();
var $th = GetTableHeader($td);
Given the following table, how would I get the corresponding table header for each td element?
<table>
<thead>
<tr>
<th id="name">Name</th>
<th id="address">Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>1 High Street</td>
</tr>
</tbody>
</table>
Given that I currently have any of the td
elements available to me already, how could I find the corresponding th
element?
var $td = IveGotThisCovered();
var $th = GetTableHeader($td);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
或者稍微简化一点
Or a little bit simplified
如果有多个表,最好使用 id 来引用该表。
It would be best to use an id to reference the table if there is more than one.
您可以使用 td 的索引来做到这一点:
You can do it by using the td's index:
处理
colspan
的解决方案我有一个基于将
td
的左边缘与相应的th
的左边缘匹配的解决方案。它应该处理任意复杂的 colspan。我修改了测试用例以显示任意
colspan
均已正确处理。现场演示
JS
CSS
HTML
Solution that handles
colspan
I have a solution based on matching the left edge of the
td
to the left edge of the correspondingth
. It should handle arbitrarily complex colspans.I modified the test case to show that arbitrary
colspan
is handled correctly.Live Demo
JS
CSS
HTML
纯JavaScript的解决方案:
Pure JavaScript's solution:
查找
td
的匹配th
,同时考虑到colspan
索引问题。Find matching
th
for atd
, taking into accountcolspan
index issues.