简体   繁体   English

如何检查jQuery元素的内容

[英]How to check content of jquery element

I'm trying to learn some jquery. 我正在尝试学习一些jQuery。 In my html page I have something like this: 在我的html页面中,我有类似以下内容:

<li>
    <ul>
       <p>This ul has text</p>
    </ul>
</li>

<li>
    <ul></ul>
</li>

I'm trying to do something if the tag 'ul' doesn't have any content 如果标签'ul'没有任何内容,我正在尝试做某事

var $ul = $li.find(' > ul')
if( $ul.text() == null || $ul.text == ""){
    alert("Empty ul");
}else{ 
    alert("Not empty ul");
}

I get the alert with "not empty ul" everytime, so the if-statement is never true. 我每次都收到“ not not ul”警报,因此if语句永远不会正确。

How can I check correctly if there is nothing inside the 'ul' tags? 如何正确检查'ul'标记内是否没有内容?

You can use :empty 您可以使用:empty

$('ul:empty').each(

If you want to check ul that only have spaces between them then you can use filter and trim to get ul 如果要检查ul之间是否只有空格,则可以使用filter和trim来获取ul

$('ul').filter(function(){
   rturn $.trim($(this).text()) == "";
});

You can use :empty selector 您可以使用:empty选择器

var $ul = $li.find(' > ul')
if( $ul.is(':empty')){
    alert("Empty ul");
}else{ 
    alert("Not empty ul");
}

In the if statement, $ul.text should have parenthesis and be $ul.text() : 在if语句中, $ul.text应该带有括号并为$ul.text()

if( $ul.text() == null || $ul.text() == ""){

You might also want to trim it, if there could be whitespace: 如果可能存在空格,您可能还想修剪它:

if( $ul.text() == null || $.trim($ul.text()) == ""){

Or use the :empty selector in combination with .is() : 或者将:empty选择器与.is()结合使用:

if($ul.is(':empty')){

Try this: 尝试这个:

$('ul:empty').each(function(){ 
   //-- Do your stuff
});

Working Example 工作实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM