jQuery 如何从表格单元格 (td) 中获取相应的表格标题 (th)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3523770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the corresponding table header (th) from a table cell (td)?
提问by djdd87
Given the following table, how would I get the corresponding table header for each td element?
鉴于下表,我将如何为每个 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>
Given that I currently have any of the td
elements available to me already, how could I find the corresponding th
element?
鉴于我目前已经拥有任何td
可用的元素,我如何才能找到相应的th
元素?
var $td = IveGotThisCovered();
var $th = GetTableHeader($td);
回答by user113716
var $th = $td.closest('tbody').prev('thead').find('> tr > th:eq(' + $td.index() + ')');
Or a little bit simplified
或者稍微简化一点
var $th = $td.closest('table').find('th').eq($td.index());
回答by Adam
var $th = $("table thead tr th").eq($td.index())
It would be best to use an id to reference the table if there is more than one.
如果有多个表,最好使用一个 id 来引用该表。
回答by doug65536
Solution that handles colspan
处理的解决方案 colspan
I have a solution based on matching the left edge of the td
to the left edge of the corresponding th
. It should handle arbitrarily complex colspans.
我有一个基于将 的左边缘匹配td
到相应th
. 它应该处理任意复杂的 colspan。
I modified the test case to show that arbitrary colspan
is handled correctly.
我修改了测试用例以显示任意colspan
处理正确。
Live Demo
现场演示
JS
JS
$(function($) {
"use strict";
// Only part of the demo, the thFromTd call does the work
$(document).on('mouseover mouseout', 'td', function(event) {
var td = $(event.target).closest('td'),
th = thFromTd(td);
th.parent().find('.highlight').removeClass('highlight');
if (event.type === 'mouseover')
th.addClass('highlight');
});
// Returns jquery object
function thFromTd(td) {
var ofs = td.offset().left,
table = td.closest('table'),
thead = table.children('thead').eq(0),
positions = cacheThPositions(thead),
matches = positions.filter(function(eldata) {
return eldata.left <= ofs;
}),
match = matches[matches.length-1],
matchEl = $(match.el);
return matchEl;
}
// Caches the positions of the headers,
// so we don't do a lot of expensive `.offset()` calls.
function cacheThPositions(thead) {
var data = thead.data('cached-pos'),
allth;
if (data)
return data;
allth = thead.children('tr').children('th');
data = allth.map(function() {
var th = $(this);
return {
el: this,
left: th.offset().left
};
}).toArray();
thead.data('cached-pos', data);
return data;
}
});
CSS
CSS
.highlight {
background-color: #EEE;
}
HTML
HTML
<table>
<thead>
<tr>
<th colspan="3">Not header!</th>
<th id="name" colspan="3">Name</th>
<th id="address">Address</th>
<th id="address">Other</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2">X</td>
<td>1</td>
<td>Bob</td>
<td>J</td>
<td>Public</td>
<td>1 High Street</td>
<td colspan="2">Postfix</td>
</tr>
</tbody>
</table>
回答by rebelliard
You can do it by using the td's index:
您可以使用 td 的索引来做到这一点:
var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');
回答by jeromej
Pure JavaScript's solution:
纯 JavaScript 的解决方案:
var index = Array.prototype.indexOf.call(your_td.parentNode.children, your_td)
var corresponding_th = document.querySelector('#your_table_id th:nth-child(' + (index+1) + ')')
回答by vsync
Find matching th
for a td
, taking into account colspan
index issues.
找到匹配th
的td
,同时考虑到colspan
指数的问题。
$('table').on('click', 'td', get_TH_by_TD)
function get_TH_by_TD(e){
var idx = $(this).index(),
th, th_colSpan = 0;
for( var i=0; i < this.offsetParent.tHead.rows[0].cells.length; i++ ){
th = this.offsetParent.tHead.rows[0].cells[i];
th_colSpan += th.colSpan;
if( th_colSpan >= (idx + this.colSpan) )
break;
}
console.clear();
console.log( th );
return th;
}
table{ width:100%; }
th, td{ border:1px solid silver; padding:5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click a TD:</p>
<table>
<thead>
<tr>
<th colspan="2"></th>
<th>Name</th>
<th colspan="2">Address</th>
<th colspan="2">Other</th>
</tr>
</thead>
<tbody>
<tr>
<td>X</td>
<td>1</td>
<td>Jon Snow</td>
<td>12</td>
<td>High Street</td>
<td>Postfix</td>
<td>Public</td>
</tr>
</tbody>
</table>
回答by ???? ????? ?????? ???? ? ?????
That's simple, if you reference them by index. If you want to hide the first column, you would:
这很简单,如果您通过索引引用它们。如果你想隐藏第一列,你会:
Copy code
复制代码
$('#thetable tr').find('td:nth-child(1),th:nth-child(1)').toggle();
The reason I first selected all table rows and then both td's and th's that were the n'th child is so that we wouldn't have to select the table and all table rows twice. This improves script execution speed. Keep in mind, nth-child()
is 1
based, not 0
.
我首先选择所有表行,然后选择作为第 n 个孩子的 td 和 th 的原因是这样我们就不必两次选择表和所有表行。这提高了脚本执行速度。请记住,nth-child()
是1
基于,不是0
。