[英]Count the number of <div> elements inside <li>
I need to know how many <div>
elements are in each <li>
. 我需要知道每个<li>
有多少<div>
元素。 So something like that: 所以像这样:
<ul>
<li>
<div> Some image 1 </div>
<div> Some image 2 </div>
<div> Some image 3 </div>
</li>
<li>
<div> Some image 4 </div>
<div> Some image 5 </div>
</li>
<li>
<div> Some image 6 </div>
<div> Some image 7 </div>
<div> Some image 8 </div>
<div> Some image 9 </div>
</li>
</ul>
The output of the function: 函数的输出:
First <li> has 3 <div>
Second <li> has 2 <div>
Third <li> has 4 <div>
var lengths = $('li').map(function(){
return $(this).find('div').length;
}).get();
Comments: 评论:
// Make an array when the input for every iteration is a <li>
$('li').map(
// Every element in the array is the amount <div>s inside the current <li>
return $(this).find('div').length;
// Produce the arry.
.get();
If you want to produce something similar to what you want easily : 如果您想轻松地产生类似于您想要的东西:
$('li').each(function() {
var length = $(this).find('div').length;
$('<div> ' + length + ' li has ' + length + 'divs </div>').appendTo('#output');
});
Output: 输出:
3 li has 3divs
2 li has 2divs
4 li has 4divs
Given a jQuery object representing your <li>
, item
, you can find out the number of <div>
s that it contains just by doing: 给定一个表示您的<li>
item
的jQuery对象,您只需执行以下操作即可找出其中包含的<div>
的数量:
item.find('div').length
But if you'd like a function with that exact output, you'll need a number → English library. 但是,如果您想要一个具有确切输出的函数,则需要一个数字→英文库。 Or, if you'll have exactly three, get your <ul>
as list
and do this: 或者,如果您刚好有三个,则将您的<ul>
作为list
并执行以下操作:
var items = list.find('li');
'First <li> has ' + items.eq(0).find('div').length + ' <div>';
'Second <li> has ' + items.eq(1).find('div').length + ' <div>';
'Third <li> has ' + items.eq(2).find('div').length + ' <div>';
$('li').each(function() {
console.log($('div', this).length);
});
$('li').each(function(i){
console.log('<li> ' + i + ' has ' + $(this).children('div').length + 'divs');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.