I'm trying to add a <li>
inside an <ul>
if the <li>
count is less or equal to 20, but the code doesn't seem to be working...
I'm using the following jQuery:
while ($(".mosaico > li").length() <= 20) {
$('.mosaico').append('<li>test</li>');
};
And nothing seems to happen.开发者_开发问答.. The HTML is:
<ul class="mosaico">
<li>
</li>
<li>
</li>
<li>
</li>
</ul>
.length
is a property, not a function.
But you shouldn't run the selector in a loop like that. Just calculate how many you need, and add them all at once.
var mosaico = $(".mosaico"),
len = 20 - mosaico.children('li').length,
str = '';
while( len-- > 0 ) {
str += '<li>test</li>';
}
mosaico.append(str);
http://jsfiddle.net/pQXNT/2
length is not a function, leave the ()
while ($(".mosaico > li").length <= 20) {
$('.mosaico').append('<li>test</li>');
};
or do it in a oneliner:
$(".mosaico")
.append(
$(new Array( 20 - $(".mosaico li").length + 1 )
.join('<li>test</li>'))
);
Use .length
instead of .length()
. Also use some tools for debugging JavaScript, such as Firebug for Firefox.
Why dont you use a for loop
for(i=0;i<20;i++)
{
$('.mosaico').append('<li>test</li>');
}
精彩评论