使用jquery隐藏与空行相关的行

时间:2011-03-28 22:40:32

标签: jquery

我有一个用于显示这样的帖子的表格结构:

<table>
    <tr><td>heading of the post</td></tr>
    <tr><td>body of the post</td></tr>
</table>

如果正文的内容恰好为空,我想要隐藏这两行。

如何使用jquery实现此目的?

忘记提及正文包含如果未正确加载$("img").error(function(){ $(this).remove(); });时删除的图像但是当我检查源时html仍然存在,所以可能它不被认为是空的

3 个答案:

答案 0 :(得分:2)

有很多方法可以做到这一点。

$('td').each(function() {
    if($(this).html()=='') {
       $(this).parent().hide()
    }
})

要获取上一行:

   $(this).parent().prev().hide()

答案 1 :(得分:1)

找到一个空列的行,然后将其隐藏。

 $('tr:has(td:empty)').hide();

答案 2 :(得分:1)

这应该可以解决问题:

$('td').filter(function () {
    return $.trim($(this).html()) == '';
}).closest('tr').prev().remove().end().remove();

:empty的问题是它必须是完全空的 - 没有空格。

另请注意,通过JavaScript更改页面不会影响页面源,后者代表原始HTML。您需要使用Firebug或Chrome开发人员工具提供的元素检查器来查看页面的“实时”状态。


稍微偏离主题,但我不明白为什么使用表结构是必要的。您可以使标记更有意义,更易于使用:

<article>
    <h1>Heading of the post</h1>
    <p>Body of the post</p>
</article>

然后jQuery可以简化为:

$('article p').filter(function () {
    return $.trim($(this).html()) == '';
}).closest('article').remove();