来自td元素的值的总和(来自不同的类元素)

时间:2013-05-18 04:09:28

标签: jquery sum

如何总计2个不同(类元素)的总值?

示例:http://jsfiddle.net/x7QuB/

var total_listed=[0,0];
var total_sold=[0,0];
$(document).ready(function(){

    var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");

    $dataRows.each(function() {
        $(this).find('.DataListed').each(function(i){        
            total_listed[i]+=parseInt( $(this).html());
        });
        $(this).find('.DataSold').each(function(i){        
            total_sold[i]+=parseInt( $(this).html());
        });
    });
    $("#sum_table td.totalColListed").each(function(i){  
        $(this).html("$"+total_listed[i]*2);
    });
    $("#sum_table td.totalColSold").each(function(i){  
        $(this).html("$"+total_sold[i]*3);
    });

});

在“.totalColListed”下的一列中,我有所有列出的值的总和,而在其他td元素“.totalColSold”中,我有所有已售商品的总和。

如何将.totalColListed+.totalColListed的总和放在新元素(td / div / etc)中,例如div“.total”?

提前谢谢。

2 个答案:

答案 0 :(得分:0)

你只想

$('.total').text(
                  parseInt($('.totalColListed').text())+
                  parseInt($('.totalColSold').text()))
                );

答案 1 :(得分:0)

代码中不需要数组。您复制的示例是计算每列的总计,i是列号。在你的代码i中是行号,所以你只是将每个数组元素指定为该行中的值,你没有总计任何东西(你看不到这个,因为其中一行有0表示它的价值,所以它不影响总数)。这是一个有效的版本。

也没有必要

var total_listed = 0;
var listed_mult = 2;
var total_sold = 0;
var sold_mult = 5;
$(document).ready(function () {

    var $dataRows = $("#sum_table tr:not('.totalColumn, .titlerow')");

    $dataRows.each(function () {
        $(this).find('.DataListed').each(function () {
            total_listed += parseInt($(this).html());
        });
        $(this).find('.DataSold').each(function () {
            total_sold += parseInt($(this).html());
        });
    });
    $("#sum_table td.totalColListed").text(total_listed * listed_mult);
    $("#sum_table td.totalColSold").text(total_sold * sold_mult);

    $('.total').text(total_listed*listed_mult + total_sold*sold_mult);
});

FIDDLE