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

Учитывая следующую таблицу, как мне получить соответствующий заголовок таблицы для каждого элемента td?

Name Address
Bob 1 High Street

Учитывая, что в настоящее время у меня уже есть какой-либо из элементов td , как мне найти соответствующий элемент?

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

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

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

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

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

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

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

Решение, которое обрабатывает 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; } }); 

CSS

 .highlight { background-color: #EEE; } 

HTML

 
Not header! Name Address Other
X 1 Bob J Public 1 High Street Postfix

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

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

Click a TD:

Name Address Other
X 1 Jon Snow 12 High Street Postfix Public

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

Скопируйте код $ (‘# thetable tr’). Find (‘td: nth-child (1), th: nth-child (1)’). Toggle ();

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

  • Выберите элемент, когда имя classа начинается с определенного слова
  • Элемент или class LIKE для jQuery?
  • jQuery или CSS-селектор, чтобы выбрать все идентификаторы, начинающиеся с некоторой строки
  • Как я могу выбрать элемент с несколькими classами в jQuery?
  • Что такое fastest children () или find () в jQuery?
  • Селектор jQuery: Id заканчивается?
  • поиск jQuery и контекст
  • Подстановочные знаки в селекторах jQuery
  • Как я могу получить идентификатор элемента с помощью jQuery?
  • Выбрать элемент по точному соответствию его содержимому
  • Каков самый быстрый способ выбора элементов-потомков в jQuery?
  • Давайте будем гением компьютера.