当列中的所有“td”为空时,如何隐藏表列?

问题描述 投票:1回答:4

我的表看起来像这样:

  <table id="mytable" width="500" border="1" cellspacing="0" cellpadding="0">
      <thead>
      <tr>
        <th>Col 1</th><th>Col 2</th><th>Col 3</th>
      </tr>
      </thead>
      <tbody>
      <tr>
        <td>abc</td>
        <td>abc</td>
        <td></td>
      </tr>
      <tr>
        <td>abc</td>
        <td>abc</td>
        <td></td>
      </tr>
      <tr>
        <td>abc</td>
        <td></td>
        <td></td>
      </tr>
      </tbody>
    </table>

如果该列的所有td都为空,我想隐藏相应的列,否则应该显示该列。

jquery html
4个回答
2
投票

一种方法是循环每个th,使用其索引在同一列中引用tds,检查它们是否全部为空,如果它们是,则隐藏该列中的所有thtd元素。

/* loop over each th */
$('th').each(function(idx, el) {

    /* check every td in the same column, see if they contain any text */
    var check = !! $('tr').find('td:eq(' + idx + ')').filter(function() {
       return $.trim( $(this).text() ).length; 
    }).length;

    /* toggle the display of each th and td in this column, based on the check above */
    $('tr').find('td:eq(' + idx + '), th:eq(' + idx + ')').toggle( check );


});

Here's a fiddle


0
投票

请试试

$("#mytable td:empty" ).hide();
$("#mytable td:not(:empty)").show();

Source


0
投票

试试这样吧

$("#mytable tbody tr").each(function (index, element) {
    if ($(element).find("td").not(':empty').length == 0) {
        $(element).hide();
    }
});

Fiddle

从第4行中删除4并运行


0
投票

如果您的专栏有像'-'这样的特定数据,请尝试以下方法:

    $('th').each(function(idx, el) {
    var check = !! $('tr').find('td:eq(' + idx + ')').filter(function() {

           //If your column has specific data like `'-'` try this one:
           return $(this).text() != '-'; 


        }).length;
        $('tr').find('td:eq(' + idx + '), th:eq(' + idx + ')').toggle( check );
    });
© www.soinside.com 2019 - 2024. All rights reserved.