Check number of list items and columnize if condition exists
Example page: http://vincent-massaro.com/columns/columns.html
On this page, there are two ordered lists, one with four items, and one with eight. I need to write a c开发者_StackOverflow社区ondition that checks how many list items are in each ordered list, and if it's more than four, split them into columns; if there are less than four, don't split into columns. The code that accomplishes this now is:
$('.mcol', this).makeacolumnlists({cols: 3, colWidth: 0, equalHeight: 'ul', startN: 1});
Thanks in advance!
One nice way is with a custom selector. Something like this:
$.expr[':'].hasmorethan4li = function(obj){
return $(obj).children('li').length > 4;
};
Lets you do this:
$('ol:hasmorethan4li').makeacolumnlists(....);
Updated: As per the OP's question from the comments, here's a version of the selector for lists with between 4 and 12 items:
$.expr[':'].hasbetween4and12li = function(obj){
var len = $(obj).children('li').length; // so we only have to run this once
return len >= 4 && len <= 12;
};
check the number of li's using $('li').size()
If you want the length
property of <li>
elements under a <ol>
, you need to get it separately for each <ol>
.
$('ol').each(function() {
$(this).children('li').length; // Gives you the number of <li>
// elements for the current <ol>
});
- http://api.jquery.com/each/
- http://api.jquery.com/children/
- http://api.jquery.com/length/
精彩评论