检查 jQuery 中 DIV 的内容是否为空

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

Check if the content of a DIV is empty in jQuery

jqueryhtmlsize

提问by RayLoveless

How do I use jQuery to check to see if the content of a <div>is empty?

如何使用 jQuery 检查 a 的内容<div>是否为空?

I tried this and is doesn't seem to be printing the correct values.

我试过了,似乎没有打印正确的值。

...
var unframed_items = $("#unframed-items");
alert(unframed_items.html().length);
...
<div id="unframed-items"> </div>
...

回答by user113716

If you mean really empty, use the empty-selector[docs]:

如果您的意思是真的空,请使用empty-selector[docs]

alert( !!$("#unframed-items:empty").length )

or

或者

alert( $("#unframed-items").is(':empty') )

If you consider whitespace-only to be empty, then use the jQuery.trim()[docs]method:

如果您认为仅空格为空,则使用jQuery.trim()[docs]方法:

alert( !$.trim( $("#unframed-items").html() ) );

回答by Rohit

<div id="portfolio"><!--portfolio-->
<div id="portfolio-works"><!--portfolio-works-->
    <div class="portfolio-works-container"></div>
</div><!--/portfolio-works-->

 $(document).ready(function(){
    if($('div.portfolio-works-container').is(':empty')){
        $('div#portfolio').hide();
    }
});

回答by Mojtaba Shateri Niasar

Use $('#elementId').is(':empty').

使用$('#elementId').is(':empty').