例如,如果值> = 20
,我需要您的帮助以获取div类的长度。<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 );
答案 0 :(得分:3)
您可以过滤其innerText大于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>
答案 1 :(得分:2)
如果您的条件匹配,则应增加长度值
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 );
答案 2 :(得分:2)
您可以使用reduce创建一个包含sum
和length
值的对象:
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>