我需要知道每个<div>
中有多少<li>
个元素。就这样:
<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>
功能的输出:
First <li> has 3 <div>
Second <li> has 2 <div>
Third <li> has 4 <div>
答案 0 :(得分:6)
var lengths = $('li').map(function(){
return $(this).find('div').length;
}).get();
<强>注释:强>
// 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();
如果您想制作类似于您想要的东西轻松:
$('li').each(function() {
var length = $(this).find('div').length;
$('<div> ' + length + ' li has ' + length + 'divs </div>').appendTo('#output');
});
输出:
3 li has 3divs
2 li has 2divs
4 li has 4divs
答案 1 :(得分:2)
给定代表<li>
,item
的jQuery对象,您可以通过执行以下操作找出它包含的<div>
个数:
item.find('div').length
但如果你想要一个具有完全输出的函数,你需要一个数字→英文库。或者,如果您只有三个,请将<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>';
答案 2 :(得分:1)
$('li').each(function() {
console.log($('div', this).length);
});
<强> jsFiddle example 强>
答案 3 :(得分:1)
$('li').each(function(i){
console.log('<li> ' + i + ' has ' + $(this).children('div').length + 'divs');
});