在 jQuery 中按 class 个名称计算 Dom 个元素

Count Dom element by class name in jQuery

我需要帮助通过 class 名称和数据日期获取元素计数:

<td data-date="2017-11-10">
    <div class="animal">Mouse</div>
    <div class="animal">Dog</div>
</td>
<td data-date="2017-11-11">
    <div class="animal">Bird</div>
</td>
<td data-date="2017-11-12">
    <div class="animal">Cat</div>
    <div class="animal">Horse</div>
    <div class="animal">Snake</div>
    <div class="animal">Tiger</div>
</td>

输出

2017-11-10: 2
2017-11-11: 1
2017-11-12: 4

谢谢。

  1. 循环每个 tr td。
  2. 使用.attr()获取属性
  3. 使用.length获取class
  4. 的元素个数

$('table tr td[data-date]').each(function() {
  var $this = $(this);



  console.log($this.attr('data-date') + " : " +
    $this.find('.animal').length)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
  <td>Not included td</td>
    <td data-date="2017-11-10">
      <div class="animal">Mouse</div>
      <div class="animal">Dog</div>
    </td>
    <td data-date="2017-11-11">
      <div class="animal">Bird</div>
    </td>
    <td data-date="2017-11-12">
      <div class="animal">Cat</div>
      <div class="animal">Horse</div>
      <div class="animal">Snake</div>
      <div class="animal">Tiger</div>
    </td>
     <td>Not included td</td>
  </tr>
</table>

给你一个解决方案

var collection = {};
$('td').each(function(){
  collection[$(this).data('date')] = $(this).children('div.animal').length;
});

console.log(collection);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td data-date="2017-11-10">
      <div class="animal">Mouse</div>
      <div class="animal">Dog</div>
    </td>
    <td data-date="2017-11-11">
      <div class="animal">Bird</div>
    </td>
    <td data-date="2017-11-12">
      <div class="animal">Cat</div>
      <div class="animal">Horse</div>
      <div class="animal">Snake</div>
      <div class="animal">Tiger</div>
    </td>
  </tr>
</table>

希望对您有所帮助。

循环并使用数据并查找

var counts = {}
$("td").each( function (i, td) {
   var $td = $(td) 
   counts[$td.data("date")] = $td.find("div").length
})
console.log(counts);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td data-date="2017-11-10">
      <div class="animal">Mouse</div>
      <div class="animal">Dog</div>
    </td>
    <td data-date="2017-11-11">
      <div class="animal">Bird</div>
    </td>
    <td data-date="2017-11-12">
      <div class="animal">Cat</div>
      <div class="animal">Horse</div>
      <div class="animal">Snake</div>
      <div class="animal">Tiger</div>
    </td>
  </tr>
</table>

你可以试试这样:

$("td").each(function() {
  console.log( $(this).prop('data-date') + ": " + $(this).children().length );
});