<ul class="taglib-ratings thumbs">
<li id="qezr_yourRating">
<a href="javascript:;" class="rating rate-up "></a>
</li>
</ul>
<ul class="taglib-ratings thumbs">
<li id="qezr_yourRating开发者_开发问答">
<a href="javascript:;" class="rating rate-up "></a>
</li>
<li id="qezr_yourRating">
<a href="javascript:;" class="rating rate-up "></a>
</li>
</ul>
I want to apply the class to the UL on base of the Count of the Inner LIs.
Like if it has two LI then the class should be like two-thumbs Like if it has one LI then the class should be like one-thumbs
I am trying this JS but not working it returns 2
jQuery(document).ready(function(){
var countLi = $(".taglib-ratings > li").size();
alert(countLi);
if(countLi == 2)
{
$(this).parent('.taglib-ratings').addClass('2-col');
alert ('this ul has 2 li');
}
else if(countLi == 1)
{
$(this).parent('.taglib-ratings').addClass('2-col');
alert ('this ul has 1 li');
}
else if(countLi > 2)
{
alert ('this ul has'+ countLi +' li');
}
});
Here is the JSbin link to the same.
http://jsbin.com/ofeda/edit
Your code does not complement your explanation... you saying you want x-thumbs, but the code extract is doing nothing like that?
Do you mean something like this instead?
$('ul.tablib-ratings').addClass(function () {
return 'thumbs-' + $(this).children('li').size();
});
You're getting "thumbs-1" instead of "one-thumbs" here, because it's a 1,000,000 times easier, and as noticed in the comments, many browsers won't appreciate 1-thumbs
You're getting "1-thumbs" instead of "one-thumbs" here, because it's a 1,000,000 times easier :P
There's a pretty obvious bug in this, if I'm understanding what you're trying to do:
else if(countLi == 1)
{
$(this).parent('.taglib-ratings').addClass('2-col'); // shouldn't this be 1-col?
alert('this ul has 1 li');
}
$('ul.tablib-ratings').each(function(i,ul){
li_amount = $(ul).find('li').length;
$(ul).addClass(li_amount+"-thumbs");
});
This will check all ul.tablib-ratings
and will add classes according to li
amounts. However the class names will be like 1-thumbs
, 2-thumbs
etc... but you can easily map the numbers to their written versions with a few lines of more code.
Hope it helps, Sinan.
You are counting the total number of li
s nested within tags with the class taglib-ratings
. Instead you need to loop through each ul
with that class, then count the number of li
s within that particular ul
$(".taglib-ratings").each(function(){
if ($(this).children('li').size() == 2 )
{
$(this).addClass('Two');
$(this).append('Two');
}
else if ($(this).children('li').size() == 1 )
{
$(this).addClass('one');
$(this).append('One');
}
});
http://jsbin.com/ofeda/2
LINK TO UPDATED JSbin
精彩评论