jQuery 使用 if 语句检查 div 是否为空

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

Using an if statement to check if a div is empty

jquery

提问by Mike Muller

I'm trying to remove a specific div if a separate div is empty. Here's what I'm using:

如果单独的 div 为空,我正在尝试删除特定的 div。这是我正在使用的:

$(document).ready(function () {
    if ('#leftmenu:empty') {
        $('#menuTitleWrapper').remove();
        $('#middlemenu').css({ 'right': '0', 'position': 'absolute' });
        $('#PageContent').css({ 'top': '30px', 'position': 'relative' });
    }
});

I think this is close but I can't figure out how to write the code to test of #leftmenu is empty. Any help is appreciated!

我认为这很接近,但我不知道如何编写代码来测试 #leftmenu 为空。任何帮助表示赞赏!

回答by user113716

You can use .is().

您可以使用.is().

if( $('#leftmenu').is(':empty') ) {
    // ...

Or you could just test the lengthproperty to see if one was found.

或者,您可以测试该length属性以查看是否找到了该属性。

if( $('#leftmenu:empty').length ) {
    // ...

Keep in mind that emptymeans no white space either. If there's a chance that there will be white space, then you can use $.trim()and check for the length of the content.

请记住,空也意味着没有空白。如果有可能会有空白,那么您可以使用$.trim()并检查内容的长度。

if( !$.trim( $('#leftmenu').html() ).length ) {
    // ...

回答by David Tang

It depends what you mean by empty.

这取决于你所说的空是什么意思。

To check if there is no text (this allows child elements that are empty themselves):

检查是否没有文本(这允许子元素本身为空):

if ($('#leftmenu').text() == '')

To check if there are no child elements or text:

要检查是否没有子元素或文本:

if ($('#leftmenu').contents().length == 0)

Or,

或者,

if ($('#leftmenu').html() == '')

回答by Dan

If you want a quick demo how you check for empty divs I'd suggest you to try this link:

如果您想要快速演示如何检查空 div,我建议您尝试此链接:

http://html-tuts.com/check-if-html-element-is-empty-or-has-children-tags/

http://html-tuts.com/check-if-html-element-is-empty-or-has-children-tags/



Below you have some short examples:

下面是一些简短的示例:

Using CSS

使用 CSS

If your div is empty without anything even no white-space, you can use CSS:

如果你的 div 是空的,甚至没有空格,你可以使用 CSS:

.someDiv:empty {
    display: none;
}

Unfortunately there is no CSS selector that selects the previous sibling element. There is only for the next sibling element: x ~ y

不幸的是,没有选择前一个兄弟元素的 CSS 选择器。只有下一个兄弟元素:x ~ y

.someDiv:empty ~ .anotherDiv {
    display: none;
}

Using jQuery

使用 jQuery

Checking text length of element with text() function

使用 text() 函数检查元素的文本长度

if ( $('#leftmenu').text().length == 0 ) {
    // length of text is 0
}

Check if element has any children tags inside

检查元素内部是否有任何子标签

if ( $('#leftmenu').children().length == 0 ) {
    // div has no other tags inside it
}

Check for empty elements if they have white-space

检查空元素是否有空格

if ( $.trim( $('.someDiv').text() ).length == 0 ) {
    // white-space trimmed, div is empty
}

回答by Arif

You can extend jQueryfunctionality like this :

您可以 像这样扩展jQuery功能:

Extend :

延长 :

(function($){
    jQuery.fn.checkEmpty = function() {
       return !$.trim(this.html()).length;
    };
}(jQuery));

Use :

用 :

<div id="selector"></div>

if($("#selector").checkEmpty()){
     console.log("Empty");
}else{
     console.log("Not Empty");
}

回答by Reid

Try this:

尝试这个:

$(document).ready(function() {
    if ($('#leftmenu').html() === "") {
        $('#menuTitleWrapper').remove();
        $('#middlemenu').css({'right' : '0', 'position' : 'absolute'});
        $('#PageContent').css({'top' : '30px', 'position' : 'relative'});
    }
});

It's not the prettiest, but it should work. It checks whether the innerHTML (the contents of #leftmenu) is an empty string (i.e. there's nothing inside of it).

这不是最漂亮的,但它应该有效。它检查innerHTML(#leftmenu 的内容)是否为空字符串(即里面没有任何内容)。

回答by Patrik Affentranger

In my case I had multiple elements to hide on document.ready. This is the function (filter) that worked for me so far:

就我而言,我有多个元素要隐藏在 document.ready 上。这是迄今为止对我有用的功能(过滤器):

$('[name="_invisibleIfEmpty"]').filter(function () {
    return $.trim($(this).html()).length == 0;
}).hide();

or .remove() rather than .hide(), whatever you prefer.

或 .remove() 而不是 .hide(),无论您喜欢什么。

FYI: This, in particular, is the solution I am using to hide annoying empty table cells in SharePoint (in addition with this condition "|| $(this).children("menu").length".

仅供参考:这尤其是我用来隐藏 SharePoint 中烦人的空表格单元格的解决方案(此外还有这个条件“|| $(this).children("menu").length”。

回答by Tadeu Luis

if (typeof($('#container .prateleira')[0]) === 'undefined') {
    $('#ctl00_Conteudo_ctrPaginaSistemaAreaWrapper').css('display','none');
}

回答by Ricardo Green

I've encountered this today and the accepted answers did not work for me. Here is how I did it.

我今天遇到了这个问题,接受的答案对我不起作用。这是我如何做到的。

if( $('#div-id *').length === 0 ) {
    // your code here...
}

My solution checks if there are any elements inside the div so it would still mark the div empty if there is only text inside it.

我的解决方案检查 div 中是否有任何元素,因此如果其中只有文本,它仍会将 div 标记为空。

回答by Zoe_NS

also you can use this :

你也可以使用这个:


    if (! $('#leftmenu').children().length > 0 ) {
         // do something : e.x : remove a specific div
    }

I think it'll work for you !

我想这对你有用!

回答by Damn

if($('#leftmenu').val() == "") {
   // statement
}