2010-04-13 114 views
1

我需要的是:
html表格5X7。在许多查询中,填充完整表格的项目少于35个。如何使用jQuery隐藏空html表格单元格?

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

谢谢。

+0

你说的是隐藏整个行或列空单元格?或者其他一些模式? – e100 2010-04-13 18:19:19

回答

3

编辑 - 改良版

// 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(); 
}); 
+0

只有在所有TD单元对于特定列都为空的情况下才有效。否则,如果您删除第一个单元格,则剩余单元格的内容每个都会左移一位(显示错误)。如果确实TD单元对于整个列都是空白的,只需删除列。 – HoldOffHunger 2016-10-12 16:59:42

1

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

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

我遇到过$('td:empty')。hide();在Safari中无法使用,所以我不使用它。我不知道它是否更新版本的jQuery更可靠。 – 2010-04-13 18:28:33

1

我投票支持Ballsacian的答案。由于某种原因,

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

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