在tbody中没有tr元素时删除表元素

时间:2010-06-25 09:23:24

标签: javascript jquery

我有这个表结构

<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标签。尽管如此,它并没有删除表元素。看一下代码

// 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 个答案:

答案 0 :(得分:4)

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

你可能会压缩到

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

<强>更新

这不起作用。看起来remove()detach()在删除tr元素后会留下某种 crud 。它就像一个空格或换行符,因为:empty选择器也检查文本节点,它根本不是空的。

所以

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

应该这样做。

参考:http://jsbin.com/esaye3/2/edit

答案 1 :(得分:0)

怎么样:

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

我无法检查元素是否为空(因为它永远不会为空,因为文本节点仍然保留在其标记内。我必须检查<table>里面是否有<tr>

相关问题