반응형
테이블 셀(td)에서 해당 테이블 헤더(th)를 가져오려면 어떻게 해야 합니까?
다음 표가 주어지면 각 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);
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. 임의로 복잡한 콜스팬을 처리해야 합니다.
테스트 케이스를 임의적인 것으로 수정했습니다.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>
순수 자바스크립트의 솔루션:
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색인 문제
document.querySelector('table').addEventListener('click', onCellClick)
function onCellClick( e ){
if( e.target.nodeName == 'TD' )
console.log( get_TH_by_TD(e.target) )
}
function get_TH_by_TD( tdNode ){
var idx = [...tdNode.parentNode.children].indexOf(tdNode), // get td index
thCells = tdNode.closest('table').tHead.rows[0].cells, // get all th cells
th_colSpan_acc = 0 // accumulator
// iterate all th cells and add-up their colSpan value
for( var i=0; i < thCells.length; i++ ){
th_colSpan_acc += thCells[i].colSpan
if( th_colSpan_acc >= (idx + tdNode.colSpan) ) break
}
return thCells[i]
}
table{ width:100%; }
th, td{ border:1px solid silver; padding:5px; }
<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>
언급URL : https://stackoverflow.com/questions/3523770/how-can-i-get-the-corresponding-table-header-th-from-a-table-cell-td
반응형
'codememo' 카테고리의 다른 글
| execvp에 대한 argv 매개 변수가 일정하지 않은 이유는 무엇입니까? (0) | 2023.10.15 |
|---|---|
| WSAGetLastError()에서 오류 문자열을 검색하려면 어떻게 합니까? (0) | 2023.10.15 |
| MySQL IN 절: 최대 인수 수 (0) | 2023.10.15 |
| SQLLechemy에서 bulk_update_mapping을 사용하여 서로 다른 값으로 여러 행 업데이트 (0) | 2023.10.15 |
| XMLHtpRequest가 헤더를 추가하지 않음 - "X-Requested-With: XMLHtpRequest" (0) | 2023.10.15 |