如何使用jquery,我可以显示具有相同类的单元格中的数字总和吗?我需要在下面显示总和:
In 2014: 105 l. //sum of every number from cell that have class "2014"
In 2013: 140 l. //sum of every number from cell that have class "2013"
In 2012: 50 l. //sum of every number from cell that have class "2012"
<td class="2014">60 l.</td>
<td class="2014">45 l.</td>
<td class="2013">60 l.</td>
<td class="2013">80 l.</td>
<td class="2012">20 l.</td>
<td class="2012">30 l.</td>
答案 0 :(得分:1)
您可以尝试编写这样的函数:
function calculateSum(className) {
var sum = 0;
$('.' + className).each(function() {
var tdText = $(this).text();
var tdNumber = parseInt(tdText.split(' ')[0]);
if(!isNaN(tdNumber)) {
sum += tdNumber;
}
});
return sum;
}
此函数只显示如何计算总和...但不确定HTML的其余部分将如何构建,因此您可能需要添加额外的逻辑来处理不同的行等...