2010-08-23 117 views
2

这是怎么回事? 我试图隐藏所有空li。jQuery loop ul li

$(document).ready(function() { 
     $("#details li").each(function() { 
      if ($(this).length == 0) { 
       $(this).css({ display: "none" }); ; 
      } 
     }); 
    }); 

标记:

<ul id="details"> 
<li>Lorem Ipsum</li> 
<li>Lorem Ipsum</li> 
<li>Lorem Ipsum</li> 
<li>Lorem Ipsum</li> 
<li></li> 
<li></li> 
<li>Lorem Ipsum</li> 
<li>Lorem Ipsum</li> 
<li>Lorem Ipsum</li> 
</ul> 

预先感谢您

+0

的了解不够精确,你的问题是什么? – greg0ire 2010-08-23 16:43:05

+0

你的问题应该更加精确,因为如果我们不知道你想要的结果是什么,就很难提出解决方案。 – Gabriel 2010-08-23 16:43:30

+0

请发布HTML。 – 2010-08-23 16:44:11

回答

6

我想你想要什么.text()长度,就像这样:

$(function() { 
    $("#details li").each(function() { 
    if ($(this).text().length == 0) { 
     $(this).css({ display: "none" }); ; 
    } 
    }); 
}); 

或者短一点:

$("#details li").filter(function() { 
    return $(this).text().length == 0; 
}).hide(); 

还是略有不同的支票,你的目的,礼貌作品@Rafael

$("#details li:empty").hide(); 
+0

在检查长度(由于HTML中的空白)之前,您应该总是使用'$ .trim()'。 – 2010-08-23 16:47:26

+0

@Marko - 如果可能有空格是的,这样做...如果你是*放心*没有(不能从这个例子中知道),正则表达式调用相同:) – 2010-08-23 16:48:31

+0

你可以做$(' #details li:empty')。hide(); – Rafael 2010-08-23 16:48:36

0

表达$(this).length不可能是零。

4

尝试使用:

if ($(this).is(':empty')) {} 

此外,你应该能够重新写上面的代码为:

$("#details li:empty").each(function() { 
    $(this).css({ display: "none" }); 
}); 

甚至:

$("#details li:empty").hide();