jQuery多个列表的单个项目计数器

时间:2018-02-19 17:10:03

标签: jquery

我有多个具有特定项目的列表。我想为每个列表显示一个项目计数器。到目前为止,我的示例代码如下所示,但我正在寻找更短的版本。可能有一个for / each函数?非常感谢任何帮助!

$('.content').each(function() {
  var one = $( '#one li' ).size();
  var two = $( '#two li' ).size();
  var three = $( '#three li' ).size();
  $( '.one' ).text(one);
  $( '.two' ).text(two);
  $( '.three' ).text(three);
});
<div class="single">List 1 <span class="itemCount one">0</span>
  <ul id="one" class="content">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
</div>
<div class="single">List 2 <span class="itemCount two">0</span>
  <ul id="two" class="content">
    <li>Item 1</li>
    <li>Item 2</li>
  </ul>
</div>
<div class="single">List 3 <span class="itemCount three">0</span>
  <ul id="three" class="content">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</div>

1 个答案:

答案 0 :(得分:0)

这应该足够了:

$('.content').each(function() {
    var $ul   = $(this);
    $ul.siblings('.itemCount').text( $ul.find('li').length );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="single">List 1 <span class="itemCount one">0</span>
  <ul id="one" class="content">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
</div>
<div class="single">List 2 <span class="itemCount two">0</span>
  <ul id="two" class="content">
    <li>Item 1</li>
    <li>Item 2</li>
  </ul>
</div>
<div class="single">List 3 <span class="itemCount three">0</span>
  <ul id="three" class="content">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</div>