如何制作jquery脚本,在表为空时隐藏表

How can I make jquery script that will hide table when table is empty?

本文关键字:隐藏 何制作 jquery 脚本      更新时间:2024-02-05

我有一些CSV到html生成器。它将CSV数据生成为html表。例如

 <table><tbody><tr><th>Name 1</th><th>Name 2</th></tr>
 <tr><td>123</td><td>123</td></tr>
 </tbody></table>

有时没有数据可生成。然后表格看起来像这样(它只显示标题)

 <table><tbody><tr><th>Name 1</th><th>Name 2</th></tr>
 </tbody></table>

在这种情况下,我想显示一些文本,而不是表格。比方说:

 <h1>There is no data man!</h1>
 <p>Contact to Us</p>

我该怎么做?

尝试此检查

   $('table').each(function(){
 var element = $(this).find('tbody tr:nth-child(2)').length;
if (element == 0) {
$(this).empty();
$(this).append(" <h1>There is no data man!</h1><p>Contact to Us</p>")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
 <table><tbody><tr><th>Name 1</th><th>Name 2</th></tr>
 </tbody></table>

您可以检查表中的行数,如果html为空,则可以更改它。

代码是这样的:

$(document).ready(function(){
    var rowCount = $('tbody > tr').length;
    if(rowCount > 1 ){ // check one more after header 
      $('table').replaceWith(" <h1>There is no data man!</h1><p>Contact to Us</p>")
    }
})

编辑:在Pimskie评论后,我更改了代码。

下面是一个工作示例https://plnkr.co/edit/CSss8LqJ0uC5pbkoPrAu?p=preview

th放入thead中。之后,一个简单的香草JS:

var table = document.querySelector('table');
var rows = document.querySelector('tbody > tr');
if (rows.length === 0) {
    table.parentNode.innerHTML = '<h1>There is no data man!</h1><p>Contact to Us</p>';
}

演示:https://jsfiddle.net/h8y1jLca/3/

编辑

如果由于某种原因无法将th放置在thead中,这也适用:https://jsfiddle.net/h8y1jLca/4/

var tbody = $("#incidents tbody");
if (tbody.children().length == 0) {
alert('There is no data man! Contact us');
   
}
else
{
alert('Table contains some data');
}
Try This One
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div>
<table id="incidents">
    <tbody>
        <tr><td>one</td></tr>
        <tr><td>two</td></tr>
        <tr><td>three</td></tr>
    </tbody>
</table>
</div>