2010-04-13 80 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崩潰。 :)

相關問題