当tbody中没有tr元素时,删除表格元素。

4

我有这个表格的结构

<table id="latest" class="debt">
    <thead>
    <tr>
        <th width="50">Credor</th>
        <th width="50">Devedor</th>
        <th>Motivo</th>
        <th width="80">Valor</th>
        <th width="10"></th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($this->latest as $latest) { ?>
        <tr <?php if ($latest->reg_value < 0) { echo "class='error'"; } ?>>
        <td><?php echo $latest->findParentRow('Application_Model_DbTable_Names','Creditor')->nam_name; ?></td>
        <td><?php echo $latest->findParentRow('Application_Model_DbTable_Names','Debtor')->nam_name; ?></td>
        <td><?php echo $latest->reg_reason; ?></td>
        <td>R$ <?php echo number_format(abs($latest->reg_value), 2, ',', ' ')?></td>
        <td><a href="#" id="<?php echo $latest->reg_id; ?>" class="delete"><img src="http://192.168.0.102/libraries/css/blueprint/plugins/buttons/icons/cross.png" alt=""/></a></td>
        </tr>
    <?php } ?>
    </tbody>
</table>

每一行都有一个删除按钮,使用AJAX并删除tr元素本身。当所有行都被删除时,可能会发生tbody变为空的情况,此时我希望删除整个表格。
我知道有一个伪选择器$('#latest tbody:empty'),但这只选择tbody。当tbody为空或类似情况时,我想选择整个表格。
编辑回答后:
我删除所有行后检查了元素:只有thead标签和tbody标签。尽管如此,它仍未删除表格元素。请看代码。
// TR Fading when deleted
$('.delete').live('click', function() {
    $.ajax({
    type: 'POST',
    url: 'history/delete/id/'+$(this).attr('id')
    });
    $(this).closest('tr').fadeOut('slow', function() {
    $(this).remove();
    if($(this).closest('table').find('tbody').is(':empty'))
        $('#latest').remove();
    });
    return false;
});
5个回答

4
if($('#latest tbody').is(':empty'))
   $('#latest').remove();

你可以将此压缩为:
$('#latest tbody:empty').parent().remove();

更新

这种方法不起作用。看起来remove()detach()在移除tr元素后确实会留下某种残留物。它可能是空格或换行符,因此由于:empty选择器还会检查文本节点,因此它并不是空的。

因此

if($('#latest tbody').children().length() < 1)
   $('#latest').remove();

应该可以解决问题。
参考:http://jsbin.com/esaye3/2/edit

我删除所有行后检查了元素:只有 <tbody></tbody> 和 thead 标签在 <table> 标签内。但是,它并没有删除表格元素。请查看我的代码 http://snipt.org/Qou 谢谢 - Rodrigo Souza
从你的代码来看,你或许应该在 if 语句中使用 $(this).closest('table').find('tbody').is(':empty') - jAndy
为什么不带if语句的代码在这种情况下不起作用?我为什么要使用find()函数? - Rodrigo Souza
抱歉,我很无知,但它仍然不起作用。看看现在的样子:http://snipt.org/Qou - Rodrigo Souza
哇..我测试了一下。看起来.remove()detach()会移除元素,但是它们会留下一些空格或换行符,所以由于:empty也检查文本节点,因此它不为空。使用if($('#latest tbody').children().length() < 1)作为语句! - jAndy
首先,你提供了错误的解决方案,但人们却投了赞成票。然后你又添加了一个与我的解决方案非常相似的解决方案...哇...做得好啊,伙计们。 - Gert Grenander

0

这样怎么样:

$('#latest tbody:empty').parent(); 

0
$("#latest:has('tbody:empty')").remove();

0
if ($('#latest tbody').children().length==0) {
  $('#latest').remove();
};

0

我无法检查元素是否为空,因为文本节点仍然存在于其标记内部,所以它永远不会为空。我必须检查 <table> 是否包含 <tr>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接