5

使用 jQuery,我如何遍历每个嵌套的 ul.item,计算 LI 的数量,并在该页面上的父 span.someClass 中返回该大小/长度?

<ul>
  <li><span class="someClass">3</span>
    <ul class="item" style="display:none">
      <li>count me</li>
      <li>count me</li>
      <li>count me</li>
    </ul>
  </li>
  <li><span class="someClass">1</span>
    <ul class="item" style="display:none">
      <li>count me</li>
    </ul>
  </li>
  <li><span class="someClass">2</span>
    <ul class="item" style="display:none">
      <li>count me</li>
      <li>count me</li>
    </ul>
  </li>
</ul>
4

7 回答 7

5
$("ul.item").each(function() {
    // reusabilty
    var context = $(this);
    // count and populate
    context.prev(".someClass").text(context.children().length);
});

如果这些元素总是紧接您的元素之前.someClass,则省略调用。在那种情况下,过滤是不必要的,也是多余的。prev()spanulprev

于 2012-11-21T16:54:05.247 回答
3

尝试这个,

现场演示

 $('.someClass').each(function(){    
     $(this).text($(this).next('ul').find('li').length);
 })​
于 2012-11-21T16:51:50.510 回答
1

您可以使用text方法:

$('.someClass').text(function(){
   return $(this).next().find('li').length
})

http://jsfiddle.net/EEsRR/

于 2012-11-21T16:54:50.617 回答
1
<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
         $(function() { 
            var count = 0;
            $('ul').each(function(){
                if(count != 0){

                    var len = $(this).find('li').length;

                    $(this).parent().find('.someClass').html(len);
                }
                count++;

            })  
         });

    </script>
</head>
<body>
<ul>
  <li><span class="someClass"></span>
    <ul class="item" style="display:none">
      <li>count me</li>
      <li>count me</li>
      <li>count me</li>
    </ul>
  </li>
  <li><span class="someClass"></span>
    <ul class="item" style="display:none">
      <li>count me</li>
    </ul>
  </li>
  <li><span class="someClass"></span>
    <ul class="item" style="display:none">
      <li>count me</li>
      <li>count me</li>
    </ul>
  </li>
</ul>
</body>
</html>
于 2012-11-21T17:05:01.717 回答
0
​$("ul.item").each(function() {
    var _c = $(this);
    _c.siblings("span.someClass").html(_c.children("li").length);
});​
于 2012-11-21T16:58:32.123 回答
0

<li>使用 jQuery循环遍历每个:

$(document).ready(function(){

  var howMany;
  // loop through every span.someClass
  $('.someClass').each(function(){
    // loop through every <li> within that span.someClass
    $('li').each(function(){
      // .index() is the current index of the $(this) object, it starts at 0, therefore .index()+1
      howMany = $(this).index()+1;
    });
    // Write your counted <li> in your <span> with .text(), manipulate the text within the <span> tags
    $(this).text(howMany);
  });
});

它奏效了吗?

于 2012-11-21T17:04:11.907 回答
-1
$('#yourelementid > li').length; 

这将为您工作,而不是使用任何循环

于 2014-04-02T09:39:08.680 回答