如何从表格单元格(td)中获取相应的表格标题(th)?

发布于 2024-09-15 07:22:21 字数 587 浏览 4 评论 0原文

给定下表,我如何获取每个 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);

Given the following table, how would I get the corresponding table header for each td element?

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

Given that I currently have any of the td elements available to me already, how could I find the corresponding th element?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

暖阳 2024-09-22 07:22:21
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 = $td.closest('tbody').prev('thead').find('> tr > th:eq(' + $td.index() + ')');

Or a little bit simplified

var $th = $td.closest('table').find('th').eq($td.index());
〃安静 2024-09-22 07:22:21
var $th = $("table thead tr th").eq($td.index())

如果有多个表,最好使用 id 来引用该表。

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

It would be best to use an id to reference the table if there is more than one.

臻嫒无言 2024-09-22 07:22:21

您可以使用 td 的索引来做到这一点:

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

You can do it by using the td's index:

var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');
夜空下最亮的亮点 2024-09-22 07:22:21

处理 colspan 的解决方案

我有一个基于将 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>

Solution that handles colspan

I have a solution based on matching the left edge of the td to the left edge of the corresponding th. It should handle arbitrarily complex colspans.

I modified the test case to show that arbitrary colspan is handled correctly.

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>
流星番茄 2024-09-22 07:22:21

纯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) + ')')

Pure JavaScript's solution:

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) + ')')
时光是把杀猪刀 2024-09-22 07:22:21

查找 td 的匹配 th,同时考虑到 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>

Find matching th for a td, taking into account colspan index issues.

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>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文