如何从表格单元格(td)中获取相应的表格标题?

djd*_*d87 83 jquery jquery-selectors

鉴于下表,我如何获得每个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>
Run Code Online (Sandbox Code Playgroud)

鉴于我目前已经有任何td可用的元素,我怎么能找到相应的th元素?

var $td = IveGotThisCovered();
var $th = GetTableHeader($td);
Run Code Online (Sandbox Code Playgroud)

use*_*716 134

var $th = $td.closest('tbody').prev('thead').find('> tr > th:eq(' + $td.index() + ')');
Run Code Online (Sandbox Code Playgroud)

或者有点简化

var $th = $td.closest('table').find('th').eq($td.index());
Run Code Online (Sandbox Code Playgroud)

  • colspans怎么样? (14认同)
  • 如果你在表中放置更多的表,使用`.parent('table')`而不是`.closest('table')` (2认同)

Ada*_*dam 8

var $th = $("table thead tr th").eq($td.index())
Run Code Online (Sandbox Code Playgroud)

如果有多个,最好使用id来引用表.


reb*_*ard 5

您可以使用 td 的索引来做到这一点:

var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');
Run Code Online (Sandbox Code Playgroud)


dou*_*536 5

处理的解决方案 colspan

我具有基于的左侧边缘相匹配的溶液td到相应的左边缘th。它应该处理任意复杂的colspans。

我修改了测试用例以显示任意colspan处理正确。

现场演示

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;
  }
});
Run Code Online (Sandbox Code Playgroud)

的CSS

.highlight {
  background-color: #EEE;
}
Run Code Online (Sandbox Code Playgroud)

的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>
Run Code Online (Sandbox Code Playgroud)