如果内容为空,则隐藏div

时间:2011-11-29 16:11:40

标签: javascript jquery html hide

哲学泡沫就像一个引用/语音泡沫div样式,里面有一个sharepoint控件,richHtmlField允许用户在编辑页面时输入内容,但如果用户选择将其留空,则不会有内容div所以只有气泡会出现在页面中看起来很有趣所以我想在没有用户输入或基本上div是空的时候隐藏整个div?你是如何在jquery中做到这一点的?

<div class="philosophy-bubble">
<PublishingWebControls:RichHtmlField FieldName="carephilosophy" runat="server"></PublishingWebControls:RichHtmlField>
</div>  

3 个答案:

答案 0 :(得分:19)

使用jQuery的:empty选择器:

$('.philosophy-bubble:empty').hide();

这是a working fiddle

<强>替代

您还可以使用filter()函数查找所有空div并隐藏:

//All divs
$('div').filter(function() {
        return $.trim($(this).text()) === ''
}).hide()

//div's with a certain class
$('.philosophy-bubble').filter(function() {
        return $.trim($(this).text()) === ''
}).hide()

//div with a specific ID
$('#YourDivID').filter(function() {
        return $.trim($(this).text()) === ''
}).hide()

...等。

注意: :empty选择器效率更高。 See jsPerf

答案 1 :(得分:-1)

var myDiv =  $('#myDiv');

if (myDiv.text() == '')
{
    myDiv.hide();
}

答案 2 :(得分:-1)

类似的东西:

if ($('.philosophy-bubble').is(":empty")){
    $('.philosophy-bubble').hide();
}

这是一个小提琴:http://jsfiddle.net/IrvinDominin/XYr9T/1/

修改

更好地使用:

$('.philosophy-bubble:empty').hide()

http://jsfiddle.net/IrvinDominin/XYr9T/3/