2017-06-27 148 views
1

我輸出該表:如果沒有TR,隱藏表

<table class="table-example"> 
    <thead> 
    <tr> 
     <th scope="col">Location</th> 
     <th scope="col">Description</th> 
     <th scope="col">Status</th> 
     <th scope="col">Eta Fix</th> 
    </tr> 
    </thead> 
    <tbody></tbody> 
</table> 

我需要整個表不顯示,如果是TBODY空如上

使用上這個變化的嘗試:

$(function(){ 
    if ($('.table-example > tbody').length == 0){ 
    $('.table-example).hide(); 
    } 
}); 

我在做什麼錯?

+0

你找TBODY元素有數量.table-example而不是tr元素。將選擇器更改爲「.table-example> tbody tr」 – SidTheBeard

回答

1

試試這個:

$(function(){ 
 
    if ($(".table-example > tbody > tr").length == null || $(".table-example > tbody > tr").length == 0){ 
 
    $(".table-example").hide(); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table class="table-example"> 
 
    <thead> 
 
    <tr> 
 
    <th scope="col">Location</th> 
 
    <th scope="col">Description</th> 
 
    <th scope="col">Status</th> 
 
    <th scope="col">Eta Fix</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody></tbody> 
 
</table>

+0

謝謝:) :) – Fento

0
$(function() { 

    if ($('.table-example > tbody > tr').length == 0){ 
    $('.table-example').hide(); 
    } 

}); 

您可以使用.table-example > tbody > tr和你在$('.table-example').hide();失蹤「。 我希望它能爲你工作。

0

如果表中存在tbody標記,則選擇器$('。table-example> tbody')將返回一個長度。相反,你需要的tbody內檢查任何元素:

$(function(){ 
    if ($('.table-example tbody *').length == 0){ 
    $('.table-example).hide(); 
    } 
}); 
2

可以使用:has選擇或方法與:empty選擇沿

$('.table-example').has('tbody:empty').hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table class="table-example"> 
 
    <thead> 
 
    <tr> 
 
    <th scope="col">Location</th> 
 
    <th scope="col">Description</th> 
 
    <th scope="col">Status</th> 
 
    <th scope="col">Eta Fix</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody></tbody> 
 
</table>