我正在创建一个发票表,其中我有一个具有相同类的表。我想计算同一行的百分比,找出每个产品的折扣价,然后在计算总和后将其显示到test_sum
并显示给total_sum
。伙计们,我需要帮助。
<tr>
<td class="test_charge">50</td>
<td class="test_discount">10</td>
<td class="test_sum">Sum:</td>
</tr>
<tr>
<td class="test_charge">40</td>
<td class="test_discount">5</td>
<td class="test_sum">Sum:</td>
</tr>
<tr>
<td class="total_sum">Total: </td>
</tr>
这是我的代码无效:
var sum = 0.0;
$('.test_sum').each(function()
{
sum += parseFloat($(this).html());
});
$('.total_sum').html(sum);
抱歉我以前使用过ID时犯了一个愚蠢的错误,我已将其替换为class
。
答案 0 :(得分:1)
var total = 0;
// For each item calculate the sum and increase the total sum
$('.item').each(function() {
var $this = $(this),
charge = Number($this.find('.item-charge').text()),
discount = Number($this.find('.item-discount').text());
var sum = charge - discount;
$this.find('.item-sum').text("Sum: " + sum);
total += sum;
});
$('.total-sum').text("Total: " + total);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="item">
<td class="text-center item-charge">50</td>
<td class="text-center item-discount">10</td>
<td class="text-cente item-sum">Sum:</td>
</tr>
<tr>
<tr class="item">
<td class="text-center item-charge">40</td>
<td class="text-center item-discount">5</td>
<td class="text-center item-sum">Sum:</td>
</tr>
<tr class="item">
<td class="text-center item-charge">100</td>
<td class="text-cente item-discount">10</td>
<td class="text-center item-sum">Sum:</td>
</tr>
<tr>
<td colspan="3" class="total-sum">Total: </td>
</tr>
</tbody>
</table>
&#13;
答案 1 :(得分:0)
如果你使用班级
var total = 0;
$( "table tr" ).each(function( index ) {
var found = $( this ).find('.test_charge')
if(found) { // check for <TR>
total += parseInt(found.text()) // be sure what you are doing with parseInt
}
});