Javascript jQuery 中列的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10802244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:59:59  来源:igfitidea点击:

Sum total for column in jQuery

javascriptjquery

提问by Redbox

The following code isn't working. I need to sum all by column as you can see on jsfiddle. What's going wrong?

以下代码不起作用。正如您在jsfiddle 上看到的那样,我需要按列汇总所有内容。怎么了?

HTML

HTML

<table id="sum_table" width="300" border="1">
    <tr>
        <td>Apple</td>
        <td>Orange</td>
        <td>Watermelon</td>
    </tr>
    <tr>
        <td class="rowDataSd">1</td>
        <td class="rowDataSd">2</td>
        <td class="rowDataSd">3</td>
    </tr>
    <tr>
        <td class="rowDataSd">1</td>
        <td class="rowDataSd">2</td>
        <td class="rowDataSd">3</td>
    </tr>
    <tr>
        <td class="rowDataSd">1</td>
        <td class="rowDataSd">2</td>
        <td class="rowDataSd">3</td>
    </tr>
    <tr class="totalColumn">
        <td class="totalCol">Total:</td>
        <td class="totalCol">Total:</td>
        <td class="totalCol">Total:</td>
    </tr>
</table>

Javascript

Javascript

$(document).ready(function(){


   $(".rowDataSd").each(function() {
      newSum.call(this);
    });

});


function newSum() {
    var $table = $(this).closest('table');
    var total = 0;

    $(this).attr('class').match(/(\d+)/)[1];

$table.find('tr:not(.totalColumn) .rowDataSd').each(function()  {
        total += parseInt($(this).html());

});

$table.find('.totalColumn td:nth-child('')').html(total);
}

回答by Aymen

Here is a jsffile. hope this helps

这是一个jsffile。希望这可以帮助

  <table id="sum_table" width="300" border="1">
        <tr class="titlerow">
            <td>Apple</td>
            <td>Orange</td>
            <td>Watermelon</td>
        </tr>
        <tr>
            <td class="rowDataSd">1</td>
            <td class="rowDataSd">2</td>
            <td class="rowDataSd">3</td>
        </tr>
        <tr>
            <td class="rowDataSd">1</td>
            <td class="rowDataSd">2</td>
            <td class="rowDataSd">3</td>
        </tr>
        <tr>
            <td class="rowDataSd">1</td>
            <td class="rowDataSd">5</td>
            <td class="rowDataSd">3</td>
        </tr>
        <tr class="totalColumn">
            <td class="totalCol">Total:</td>
            <td class="totalCol">Total:</td>
            <td class="totalCol">Total:</td>
        </tr>
    </table> 
<script>
       var totals=[0,0,0];
        $(document).ready(function(){

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

            $dataRows.each(function() {
                $(this).find('.rowDataSd').each(function(i){        
                    totals[i]+=parseInt( $(this).html());
                });
            });
            $("#sum_table td.totalCol").each(function(i){  
                $(this).html("total:"+totals[i]);
            });

        });
</script>

回答by Richard

jsFiddle with example

jsFiddle 示例

To achieve this, we can take full advantage of the theadand tfoottags within the tableelement. With minor changes, we have the following:

为了实现这一点,我们可以充分利用元素中的theadtfoot标签table。通过细微的更改,我们有以下内容:

HTML

HTML

<table id="sum_table" width="300" border="1">
    <thead>                
        <tr>
            <th>Apple</th>
            <th>Orange</th>
            <th>Watermelon</th>
        </tr>
    </thead>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tfoot>
        <tr>
            <td>Total:</td>
            <td>Total:</td>
            <td>Total:</td>
        </tr>
    </tfoot>
</table>???????????????

This then allows us to target more specifically the elements we want, i.e. how many columns are there, and what is the "total" cell.

然后,这允许我们更具体地定位我们想要的元素,即有多少列,以及“总”单元格是多少。

JavaScript

JavaScript

$(document).ready(function()
{
    $('table thead th').each(function(i)
    {
        calculateColumn(i);
    });
});

function calculateColumn(index)
{
    var total = 0;
    $('table tr').each(function()
    {
        var value = parseInt($('td', this).eq(index).text());
        if (!isNaN(value))
        {
            total += value;
        }
    });

    $('table tfoot td').eq(index).text('Total: ' + total);
}?

回答by Jamiec

$('#sum_table tr:first td').each(function(){
   var $td = $(this); 

    var colTotal = 0;
    $('#sum_table tr:not(:first,.totalColumn)').each(function(){
        colTotal  += parseInt($(this).children().eq($td.index()).html(),10);
    });

    $('#sum_table tr.totalColumn').children().eq($td.index()).html('Total: ' + colTotal);
});

Live example: http://jsfiddle.net/unKDk/7/

现场示例:http: //jsfiddle.net/unKDk/7/

回答by lucuma

An alternate way:

另一种方式:

$(document).ready(function(){   
    for (i=0;i<$('#sum_table tr:eq(0) td').length;i++) {
       var total = 0;
        $('td.rowDataSd:eq(' + i + ')', 'tr').each(function(i) {
           total = total + parseInt($(this).text());
        });            
        $('#sum_table tr:last td').eq(i).text(total);
    }

});

Example: http://jsfiddle.net/lucuma/unKDk/10/

示例:http: //jsfiddle.net/lucuma/unKDk/10/

回答by jbabey

This is easily accomplished with a little tweaking of the classes on your table:

这很容易通过对表中的类进行一些调整来实现:

HTML:

HTML:

<table id="sum_table" width="300" border="1">
    <tr>
        <td>Apple</td>
        <td>Orange</td>
        <td>Watermelon</td>
    </tr>
    <tr>
        <td class="col1">1</td>
        <td class="col2">2</td>
        <td class="col3">3</td>
    </tr>
    <tr>
        <td class="col1">1</td>
        <td class="col2">2</td>
        <td class="col3">3</td>
    </tr>
    <tr>
        <td class="col1">1</td>
        <td class="col2">2</td>
        <td class="col3">3</td>
    </tr>
    <tr>
        <td class="total">Total:</td>
        <td class="total">Total:</td>
        <td class="total">Total:</td>
    </tr>
</table>?

JS:

JS:

var getSum = function (colNumber) {
    var sum = 0;
    var selector = '.col' + colNumber;

    $('#sum_table').find(selector).each(function (index, element) {
        sum += parseInt($(element).text());
    });  

    return sum;        
};

$('#sum_table').find('.total').each(function (index, element) {
    $(this).text('Total: ' + getSum(index + 1)); 
});

http://jsfiddle.net/unKDk/9/

http://jsfiddle.net/unKDk/9/

回答by jwatts1980

I know this has been well answered by now, but I started working on this solution earlier before all the answers came through and wanted to go ahead and post it.

我知道现在已经很好地回答了这个问题,但我在所有答案都通过之前就开始研究这个解决方案,并想继续发布它。

This solution works with the HTML as you posted it, and assumes 4 things: 1) the first row is the header row, 2) the last row is the totals row, 3) each row has equal columns, and 4) the columns contain integers. In this case, only the table needs to be identified.

此解决方案适用于您发布的 HTML,并假设 4 件事:1) 第一行是标题行,2) 最后一行是总计行,3) 每行具有相等的列,以及 4) 列包含整数。在这种情况下,只需要识别表。

$(document).ready(function(){
    totalRows("#sum_table");
});

function totalRows(tableSelector) {
    var table = $(tableSelector);
    var rows = table.find("tr");
    var val, totals = [];

    //loop through the rows getting values in the rowDataSd columns
    rows
        .each(function(rIndex) {
            if (rIndex > 0 && rIndex < (rows.length-1)) { //not first or last row
                //loop through the columns
                $(this).find("td").each(function(cIndex) {
                    val = parseInt($(this).html());
                    (totals.length>cIndex) ? totals[cIndex]+=val : totals.push(val);
                });
            }
        })
        .last().find("td").each(function(index) {
            val = (totals.length>index) ? totals[index] : 0;
            $(this).html( "Total: " + val );
        });
}
?
?

回答by Tyler Crompton

Here you go sir! http://jsfiddle.net/47VDK/

来了,先生!http://jsfiddle.net/47VDK/