【问题标题】:How can I get the corresponding table column (td) from a table header (th)?如何从表头 (th) 中获取相应的表列 (td)?
【发布时间】:2011-11-15 20:44:31
【问题描述】:

我想获取表头的整个列。

比如我想选择表头“Address”隐藏地址栏,选择“Phone”表头显示对应栏。

<table>
<thead> 
    <tr>
        <th id="name">Name</th>
        <th id="address">Address</th>
        <th id="address" class='hidden'>Address</th>
    </tr>
</thead> 
<tbody>
    <tr>
        <td>Freddy</td>
        <td>Nightmare Street</td>
        <td class='hidden'>123</td>
    </tr>
    <tr>
        <td>Luis</td>
        <td>Lost Street</td>
        <td class='hidden'>3456</td>
    </tr>
</tbody>

我想做http://www.google.com/finance?q=apl 之类的事情(请参阅相关公司表)(点击“添加或删除列”链接)

【问题讨论】:

标签: javascript jquery


【解决方案1】:

这样的事情会起作用 -

$('th').click(function() {
    var index = $(this).index()+1;
    $('table td:nth-child(' + index + '),table th:nth-child(' + index + ')').hide()
});

如果您单击标题,上面的代码将隐藏相关列,但可以更改逻辑以满足您的要求。

演示 - http://jsfiddle.net/LUDWQ/

【讨论】:

    【解决方案2】:

    通过对您的 HTML 进行一些简单的修改,我会执行以下操作(无框架 JS):

    HTML:

    <input class="chk" type="checkbox" checked="checked" data-index="0">Name</input>
    <input class="chk" type="checkbox" checked="checked" data-index="1">Address</input>
    <input class="chk" type="checkbox" checked="checked" data-index="2">Phone</input>
    
    <table id="tbl">
    <thead> 
        <tr>
            <th>Name</th>
            <th>Address</th>
            <th>Phone</th>
        </tr>
    </thead> 
    <tbody>
        <tr>
            <td>Freddy</td>
            <td>Nightmare Street</td>
            <td>123</td>
        </tr>
        <tr>
            <td>Luis</td>
            <td>Lost Street</td>
            <td>3456</td>
        </tr>
    </tbody>
    

    Javascript:

    var cb = document.getElementsByClassName("chk");
    var cbsz = cb.length;
    
    for(var n = 0; n < cbsz ; ++n) {
        cb[n].onclick = function(e) {
            var idx = e.target.getAttribute("data-index");
            toggleColumn(idx);
        }
    }
    
    function toggleColumn(idx) {
        var tbl = document.getElementById("tbl");
        var rows = tbl.getElementsByTagName("tr");
        var sz = rows.length;
    
        for(var n = 0; n < sz; ++n) {
            var el = n == 0 ? rows[n].getElementsByTagName("th")[idx] : rows[n].getElementsByTagName("td")[idx];
            el.style.display = el.style.display === "none" ? "table-cell" : "none";
        }
    }
    

    http://jsfiddle.net/dbrecht/YqUNz/1/

    我添加了复选框,因为将单击绑定到列标题没有意义,因为您将无法切换可见性,只能隐藏它们。

    【讨论】:

    • 我没有对你投反对票,但我猜这是因为你的答案很重,因为这个问题被标记为 jquery,但你用更重的普通 JS 回答。例如,'table-cell' 的麻烦问题被 $().hide() 很好地封装了。但是你的答案是最完整的。
    【解决方案3】:

    你可以用 CSS 做一些事情,比如:

    <html>
    <head>
        <style>
            .c1 .c1, .c2 .c2, .c3 .c3{
                display:none;
            }
        </style>
    </head>
    <body>
    <table class="c2 c3">
        <thead> 
            <tr>
                <th id="name" class="c1">Name</th>
                <th id="address" class="c2">Address</th>
                <th id="phone" class="c3">Phone</th>
            </tr>
        </thead> 
        <tbody>
            <tr>
                <td class="c1">Freddy</td>
                <td class="c2">Nightmare Street</td>
                <td class="c3">123</td>
            </tr>
            <tr>
                <td class="c1">Luis</td>
                <td class="c2">Lost Street</td>
                <td class="c3">3456</td>
            </tr>
        </tbody>
    </table>
    </body>
    </html>
    

    要隐藏列,您可以使用 Javascript 将相应的类添加到表中。这里 c2 和 c3 被隐藏了。

    您可以在样式标签中动态添加 .c1、.c2、...,或定义最大数量。

    【讨论】:

      【解决方案4】:

      最简单的方法是为每个 td 添加一个与标头类匹配的类。当您单击 时,它会检查类,然后隐藏该类的每个 td。由于只有该列中的 s 会隐藏该类,因此它会有效地隐藏该列。

      <table>
        <thead>
          <th>Name</th>
          <th>Address</th>
        </thead>
        <tbody>
          <tr>
             <td class="Name">Joe</td>
             <td class="Address">123 Main St.
        </tbody>
      </table>
      

      脚本类似于:

      $('th').click( function() {
        var col = $(this).html(); // Get the content of the <th>
        $('.'+col).hide(); // Hide everything with a class that matches the col value.
      });
      

      反正就是这样。这可能比它需要的更冗长,但它应该展示原理。

      另一种方法是简单地计算有问题的列有多少,然后循环遍历每一行并隐藏同样多列的 td。例如,如果您想隐藏地址列并且它是第 3 列(索引 2),那么您将遍历每一行并隐藏第三行(索引 2)。

      祝你好运..

      【讨论】:

      • 呃,您将如何切换列的可见性n 次而不是仅仅隐藏它?..
      • jQuery 有一个 .toggle() 函数,可以用来代替 hide()。我正在演示如何隐藏列。将其带回来并不困难,并且遵循相同的基本原则。
      • 啊..你知道吗?我误解了您的代码(以为您也隐藏了列标题,这使得 no 有意义;))。删除了反对票:)
      【解决方案5】:

      模拟 Google 财经显示/隐藏列功能:

      http://jsfiddle.net/b9chris/HvA4s/

      $('#edit').click(function() {
          var headers = $('#table th').map(function() {
              var th =  $(this);
              return {
                  text: th.text(),
                  shown: th.css('display') != 'none'
              };
          });
      
          var h = ['<div id=tableEditor><button id=done>Done</button><table><thead><tr>'];
          $.each(headers, function() {
              h.push('<th><input type=checkbox',
                     (this.shown ? ' checked ' : ' '),
                     '/> ',
                     this.text,
                     '</th>');
          });
          h.push('</tr></thead></table></div>');
          $('body').append(h.join(''));
      
          $('#done').click(function() {
              var showHeaders = $('#tableEditor input').map(function() { return this.checked; });
              $.each(showHeaders, function(i, show) {
                  var cssIndex = i + 1;
                  var tags = $('#table th:nth-child(' + cssIndex + '), #table td:nth-child(' + cssIndex + ')');
                  if (show)
                      tags.show();
                  else
                      tags.hide();
              });
      
              $('#tableEditor').remove();
              return false;
          });
      
          return false;
      });
      

      【讨论】:

        【解决方案6】:
        jQuery('thead td').click( function () {
        
            var th_index = jQuery(this).index();
        
            jQuery('#my_table tbody tr').each(
                function(index) {
                    jQuery(this).children('td:eq(' + th_index + ');').each(
                        function(index) {
                            // do stuff here
                        }
                    );
                }
            );
        });
        

        【讨论】:

          【解决方案7】:

          这是这种行为的有效方法:

          http://jsfiddle.net/tycRW/

          当然,隐藏列而不隐藏标题会产生一些奇怪的结果。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-10-17
            • 1970-01-01
            • 1970-01-01
            • 2020-11-30
            • 1970-01-01
            • 2019-10-05
            • 1970-01-01
            相关资源
            最近更新 更多