【问题标题】:How can I hide empty html table cells with jQuery?如何使用 jQuery 隐藏空的 html 表格单元格?
【发布时间】:2011-02-07 14:07:29
【问题描述】:

我有一个 5×7 的 HTML 表格。在许多查询中,填写完整表格的项目少于 35 个。

在这种情况下,如何使用 jQuery(或任何其他有效方式)动态“隐藏”空单元格?

【问题讨论】:

  • 您是在谈论隐藏整行或整列空单元格吗?还是其他模式?

标签: javascript html jquery css html-table


【解决方案1】:

编辑 - 改进版

// Grab every row in your table
$('table#yourTable tr').each(function(){
  if($(this).children('td:empty').length === $(this).children('td').length){
    $(this).remove(); // or $(this).hide();
  }
});

未经测试,但逻辑上似乎合理。

// Grab every row in your table
$('table#yourTable tr').each(function(){
  var isEmpty = true;
  // Process every column
  $(this).children('td').each(function(){
    // If data is present inside of a given column let the row know
    if($.trim($(this).html()) !== '') {
      isEmpty = false;
      // We stop after proving that at least one column in a row has data
      return false;
    }
  });
  // If the whole row is empty remove it from the dom
  if(isEmpty) $(this).remove();
});

【讨论】:

  • 这仅适用于特定列的所有 TD 单元格为空白的情况。否则,如果您删除第一个单元格,其余单元格的内容将分别向左移动一个(显示错误)。如果一整列的 TD 单元格都是空白的,则删除该列。
  • 是否值得在 each 函数内分配 $this = $(this); 而不是每行转换为 jQuery 对象三次?
【解决方案2】:

显然,您需要调整选择器以满足您的特定需求:

$('td').each(function(){
  if ($(this).html() == '') {
    $(this).hide();
  }
});

【讨论】:

  • 我遇到过 $('td:empty').hide();在 Safari 中不起作用,所以我不使用它。我想知道它在较新版本的 jquery 中是否更可靠。
【解决方案3】:
$('td:empty').hide();

【讨论】:

    【解决方案4】:

    CSS empty-cells 怎么样

    table {
        empty-cells: hide;
    }
    

    【讨论】:

      【解决方案5】:

      我投票给Ballsacian's answer。不知为何,

      $('table#myTable tr:not(:has(td:not(:empty)))').hide();
      

      有一个错误。如果你删除最外层的:not(),它会如你所愿,但上面的完整表达式会使 jQuery 崩溃。

      【讨论】:

        猜你喜欢
        • 2012-05-20
        • 1970-01-01
        • 2012-08-14
        • 2012-02-18
        • 2019-01-30
        • 1970-01-01
        • 1970-01-01
        • 2017-12-11
        • 2015-05-28
        相关资源
        最近更新 更多