2011-11-29 91 views
7

哲學泡泡就像一個內部具有sharepoint控件的報價/語音泡沫div風格,richHtmlField允許用戶在編輯頁面時鍵入內容,但如果用戶選擇將其留空,div中將沒有內容,所以只有泡泡會出現在頁面中,看起來很有趣,所以我想在沒有用戶輸入或基本上div是空的時候隱藏整個div?你如何在jQuery中做到這一點?如果內容爲空,請隱藏div

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

回答

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

+0

只有當某個類的另一個DIV丟失時,我的DIV纔是空的:http://stackoverflow.com/questions/26845161/how-to-hide-a-div-if-content-are-missing。我怎樣才能應用我的代碼相同?謝謝。 – Si8

-1
var myDiv = $('#myDiv'); 

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