jQuery 如何在空时隐藏/删除 DIV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1455112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to hide/remove a DIV when empty
提问by CLiown
I have some server side HTML output I cannot deal with using pure CSS, essentially the DIV sometimes holds:
我有一些服务器端 HTML 输出,我无法使用纯 CSS 处理,本质上 DIV 有时会保存:
<div><span>Content</span></div>
or
或者
<div><p>Content</p></div>
or
或者
<div>Content</div>
or
或者
<div> </div>
When the DIV == <div> </div>
I want to remove it.
当 DIV ==<div> </div>
我想删除它。
Any ideas?
有任何想法吗?
回答by Andrew
You can do this using only CSS:
你可以只使用 CSS 来做到这一点:
div:empty { display: none }
回答by Daniel Huckstep
Even better (assuming jQuery):
更好(假设 jQuery):
$(document).ready(function() { $('div:empty').remove(); });
EDIT: The other answers are good, but the OP wanted to remove the empty item, not hide it.
编辑:其他答案很好,但 OP 想要删除空项目,而不是隐藏它。
回答by Allain Lalonde
回答by Abbey
Here's another easy way... using the filter()...
这是另一种简单的方法......使用过滤器()......
$('div').filter(function() {
return $.trim($(this).text()) === ''
}).remove()
回答by Douglas Lise
You can also use CSS-only to solve this, putting a table with style="empty-cells:hide"
around the content, and changing the div
to a td
, like this:
您也可以使用 CSS-only 来解决这个问题,style="empty-cells:hide"
在内容周围放置一个表格,并将 更改div
为 a td
,如下所示:
Before:
前:
<div>Content</div>
<div>Content</div>
After:
后:
<table style="empty-cells:hide"><tr><td>Content</td></tr></table>
<table style="empty-cells:hide"><tr><td>Content</td></tr></table>