Jak mogę pobrać odpowiedni nagłówek tabeli (th) z komórki tabeli (TD)?

Biorąc pod uwagę następującą tabelę, jak uzyskać odpowiedni nagłówek tabeli dla każdego elementu 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>

Biorąc pod uwagę, że obecnie mam już jeden z elementów td dostępnych dla mnie, Jak mogę znaleźć odpowiedni element th?

var $td = IveGotThisCovered();
var $th = GetTableHeader($td);
Author: GenericTypeTea, 2010-08-19

7 answers

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

Lub nieco uproszczone

var $th = $td.closest('table').find('th').eq($td.index());
 125
Author: user113716,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-19 16:13:04
var $th = $("table thead tr th").eq($td.index())

Najlepiej byłoby użyć identyfikatora, aby odwołać się do tabeli, jeśli jest więcej niż jedna.

 7
Author: Adam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-19 16:15:19

Możesz to zrobić używając indeksu td:

var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');
 4
Author: rebelliard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-19 16:41:00

Rozwiązanie, które obsługuje colspan

Mam rozwiązanie oparte na dopasowaniu lewej krawędzi td do lewej krawędzi odpowiadającej th. Powinien obsługiwać dowolnie złożone kolspany.

Zmodyfikowałem przypadek testowy, aby pokazać, że arbitralne colspan jest obsługiwane poprawnie.

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>
 3
Author: doug65536,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-19 03:51:26

Czyste rozwiązanie 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) + ')')
 2
Author: JeromeJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-19 01:53:25

Znajdź pasujące th dla td, biorąc pod uwagę colspan problemy z indeksem.

$('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>
 0
Author: vsync,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-10 09:43:14

To proste, jeśli odwołujesz się do nich przez indeks. Jeśli chcesz ukryć pierwszą kolumnę, możesz:

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

Powodem, dla którego najpierw wybrałem wszystkie wiersze tabeli, a następnie zarówno td, jak i th, które były n ' tym potomkiem, jest to, że nie będziemy musieli wybierać tabeli i wszystkich wierszy tabeli dwa razy. Poprawia to szybkość wykonywania skryptów. Należy pamiętać, że nth-child() jest 1 oparte, a nie 0.

 0
Author: مهدی عابدی برنامه نویس و مشاور,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-11 09:51:05