Подтвердить что ты не робот

Как я могу получить соответствующий заголовок таблицы (th) из ячейки таблицы (td)?

Учитывая следующую таблицу, как мне получить соответствующий заголовок таблицы для каждого элемента 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);
4b9b3361

Ответ 1

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

Или немного упрощено

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

Ответ 2

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

Лучше всего использовать id для ссылки на таблицу, если ее больше.

Ответ 3

Вы можете сделать это, используя индекс td:

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

Ответ 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>

Ответ 5

Чистое решение для 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) + ')')

Ответ 6

Найти соответствие 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>

Ответ 7

Это просто, если вы ссылаетесь на них по индексу. Если вы хотите скрыть первый столбец, вы бы:

Скопировать код

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

Причина, по которой я сначала выбрал все строки таблицы, а затем и td, и th, являющиеся n-ным дочерним элементом, заключается в том, что нам не нужно выбирать таблицу и все строки таблицы дважды. Это улучшает скорость выполнения скрипта. Имейте в виду, nth-child() основан на 1, а не на 0.