jQuery loop ul li
What's wrong with this? I'm trying to hide all empty li.
$(document开发者_StackOverflow中文版).ready(function() {
$("#details li").each(function() {
if ($(this).length == 0) {
$(this).css({ display: "none" }); ;
}
});
});
Markup:
<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>
Thank you in advance
I think what you want is the .text()
length, like this:
$(function() {
$("#details li").each(function() {
if ($(this).text().length == 0) {
$(this).css({ display: "none" }); ;
}
});
});
Or a bit shorter:
$("#details li").filter(function() {
return $(this).text().length == 0;
}).hide();
Or a slightly different check that works for your purposes, courtesy of @Rafael:
$("#details li:empty").hide();
Try using:
if ($(this).is(':empty')) {}
Furthermore, you should be able to re-write the above code as:
$("#details li:empty").each(function() {
$(this).css({ display: "none" });
});
Or even:
$("#details li:empty").hide();
The expression $(this).length
cannot possibly be zero.
精彩评论