代码之家  ›  专栏  ›  技术社区  ›  djdd87

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

  •  80
  • djdd87  · 技术社区  · 14 年前

    <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);
    
    7 回复  |  直到 14 年前
        1
  •  139
  •   user113716    14 年前
    var $th = $td.closest('tbody').prev('thead').find('> tr > th:eq(' + $td.index() + ')');
    

    var $th = $td.closest('table').find('th').eq($td.index());
    
        2
  •  10
  •   Adam    14 年前
    var $th = $("table thead tr th").eq($td.index())
    

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

        3
  •  5
  •   rebelliard    14 年前

    您可以使用td的索引:

    var tdIndex = $td.index() + 1;
    var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');
    
        4
  •  5
  •   doug65536    8 年前

    解决方案 colspan

    我有一个解决方案的基础上匹配的左边缘 td th . 它应该处理任意复杂的列。

    科尔斯潘

    Live Demo

    $(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>
    
        5
  •  2
  •   jeromej    8 年前

    纯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) + ')')
    
        6
  •  2
  •   vsync    3 年前

    查找匹配项 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>
        7
  •  0
  •   Mark Schultheiss    5 年前

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

    nth-child() 1 基于,而不是 0