JavaScript Div长度如果大于大于



我想要您的帮助,以便如何获得DIV类的长度,例如值> = 20

<td class="total">23</td>
<td class="total">12</td>
<td class="total">3</td>
<td class="total">42</td>

在我的示例中,我有4个班级记录。但是结果应该为2,因为只有2个记录> = 20

这是我的尝试:

   $(".total").each(function() {
      var val = $.trim( $(this).text() );
      if ( val >= 20) {
          val = parseFloat( val.replace( /^$/, "" ) );
          length = $(".total").length // but this will show me all records which is not correct
          sum += !isNaN( val ) ? val : 0;
      }
    });
    console.log( sum );
    console.log( length );

您可以在其内部的细胞上过滤大于20

console.log(
  $('.total').filter((index,td)=>parseInt(td.innerText, 10)>=20).get()
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table><tr>
<td class="total">23</td>
<td class="total">12</td>
<td class="total">3</td>
<td class="total">42</td>
</tr>
</table>

如果您的条件匹配

,则应增加长度值
var length = 0;
 $(".total").each(function() {
      var val = $.trim( $(this).text() );
      if ( val >= 20) {
          val = parseFloat( val.replace( /^$/, "" ) );
          length++;
          sum += !isNaN( val ) ? val : 0;
      }
    });
    console.log( sum );
    console.log( length );

您可以使用Reled来创建一个值的sumlength的对象:

let result = [...document.querySelectorAll('.total')].reduce((obj, itm) => {
  let val = parseFloat(itm.textContent)
  if(val >= 20) {
    obj.sum += val
    obj.length++
    obj.items.push(itm)
  }
  return obj
}, {sum: 0, length: 0, items: []})
console.log(result)
<table>
  <tr>
    <td class="total">23</td>
    <td class="total">12</td>
    <td class="total">3</td>
    <td class="total">42</td>
  </tr>
</table>

最新更新