0

我需要知道每个中有多少<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>
4

4 回答 4

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
于 2012-06-21T13:36:08.117 回答
2

<li>给定一个代表您的,的 jQuery 对象item,您可以通过执行以下操作找出<div>它包含的 s 数量:

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>';
于 2012-06-21T13:36:20.353 回答
1
$('li').each(function() {
    console.log($('div', this).length);
});​

jsFiddle 示例

于 2012-06-21T13:37:07.130 回答
1
$('li').each(function(i){
    console.log('<li> ' + i + ' has ' + $(this).children('div').length + 'divs');
});
于 2012-06-21T13:37:42.457 回答