javascript 如果内容为空,则隐藏 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8313973/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:01:06  来源:igfitidea点击:

Hide a div if content is empty

javascriptjqueryhtmlhide

提问by AJSwift

Philosophy bubble is like a quote/speech bubble div styled which has a sharepoint control inside, the richHtmlField which lets users to type in content while editing page, but if the user chooses to leave it empty, there will be no content in the div so only the bubble will show up in the page which will look funny so i wanna hide the whole div when there is no user entry or basically the div is empty?? How do you do this in jquery?

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

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

回答by James Hill

Use jQuery's :emptyselector:

使用 jQuery 的:empty选择器:

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

Here's a working fiddle.

这是一个工作小提琴

Alternative

选择

You could also use the filter()function to find all empty div's and hide:

您还可以使用该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()

..etc.

..等等。

Note:the :emptyselector will be more performant. See jsPerf.

注::empty选择将是更好的性能。请参阅 jsPerf

回答by Seth

var myDiv =  $('#myDiv');

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

回答by Irvin Dominin

Something like:

就像是:

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

here is a fiddle: http://jsfiddle.net/IrvinDominin/XYr9T/1/

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

EDIT

编辑

better by using:

更好地使用:

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

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

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