테이블 셀 (td)에서 해당 테이블 헤더 (th)를 어떻게 가져올 수 있습니까?


86

다음 테이블이 주어지면 각 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);

2
대답 중 어느 것도 내 사용 사례 인 1보다 큰 colspan을 가질 가능성을 고려하지 않습니다. (
Dexygen

1
@GeorgeJempty 내 대답 은 colspan을 처리합니다.
doug65536

답변:


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

또는 약간 단순화

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

2
당신이 당신의 테이블에 이상의 테이블을 두는 경우, 사용 .parent('table')대신에.closest('table')
Dead.Rabit

14
colspans는 어떻습니까?
bradvido 2015 년

@bradvido - 내 대답은 소요 계정에 그
VSYNC

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

둘 이상의 테이블이있는 경우 ID를 사용하여 테이블을 참조하는 것이 가장 좋습니다.


페이지에 테이블이 두 개 이상
있어이

5

처리하는 솔루션 colspan

I는 왼쪽 에지 매칭에 기초하여 솔루션이 td해당의 왼쪽 가장자리를 th. 임의로 복잡한 colspan을 처리해야합니다.

임의의 항목 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

<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>

colspan헤더와 행에서 임의의 조합을 동시에 사용하도록 테스트 케이스를 확장 했지만 여전히 작동했습니다. 이 문제가 해결되지 않는 사례가 있으면 기꺼이 듣겠습니다.
doug65536

4

td의 색인을 사용하여 수행 할 수 있습니다.

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

1
.index()0부터 시작하고 nth-child1부터 시작 한다는 것을 기억하십시오 . 따라서 결과는 하나씩 벗어납니다. : o)
user113716

3

순수 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) + ')')

1

색인 문제 를 고려 th하여에 대한 일치 를 찾습니다 .tdcolspan

$('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

색인으로 참조하면 간단합니다. 첫 번째 열을 숨기려면 다음을 수행하십시오.

코드 복사

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

처음에 모든 테이블 행을 선택한 다음 n 번째 자식 인 td와 th를 모두 선택한 이유는 테이블과 모든 테이블 행을 두 번 선택할 필요가 없기 때문입니다. 이렇게하면 스크립트 실행 속도가 향상됩니다. 명심 nth-child()한다 1,하지를 기반으로 0.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.