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

时间:2010-08-19 16:09:10

标签: 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>

鉴于我目前已经拥有任何td元素,我怎样才能找到相应的th元素?

var $td = IveGotThisCovered();
var $th = GetTableHeader($td);

7 个答案:

答案 0 :(得分:133)

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

或者稍微简化一下

var $th = $td.closest('table').find('th').eq($td.index());

答案 1 :(得分:8)

var $th = $("table thead tr th").eq($td.index())

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

答案 2 :(得分:4)

您可以使用td的索引来完成:

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

答案 3 :(得分:4)

处理colspan

的解决方案

我有一个基于匹配td左边缘到相应th左边缘的解决方案。它应该处理任意复杂的colspans。

我修改了测试用例,表明正确处理了任意colspan

Live Demo

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

.highlight {
  background-color: #EEE;
}

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>

答案 4 :(得分:1)

Pure 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) + ')')

答案 5 :(得分:1)

查找th的匹配td,并考虑colspan索引问题。

&#13;
&#13;
$('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;
}
&#13;
table{ width:100%; }
th, td{ border:1px solid silver; padding:5px; }
&#13;
<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>
&#13;
&#13;
&#13;

答案 6 :(得分:0)

如果您通过索引引用它们,那很简单。如果你想隐藏第一列,你会:

复制代码

$('#thetable tr').find('td:nth-child(1),th:nth-child(1)').toggle();

我首先选择所有表行,然后选择td和th是第n个孩子的原因是我们不必选择表和所有表行两次。这提高了脚本执行速度。请注意,nth-child()基于1,而不是0