0

如何对 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" ?

先感谢您。

4

2 回答 2

0

你只想

$('.total').text(
                  parseInt($('.totalColListed').text())+
                  parseInt($('.totalColSold').text()))
                );
于 2013-05-18T04:25:57.743 回答
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);
});

小提琴

于 2013-05-18T05:06:29.240 回答