2010-08-23 115 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();