如何获得每个动态生成的表的列的总和

How can I get the sum of a colum for each dynamically generated table?

本文关键字:何获得 动态      更新时间:2023-10-10

我有一个页面,其中包含每个日期动态生成的表。每个日期都有一个列,显示每个产品的支付金额。例如,

<table class="table">
        <thead>
            <tr>
                <th>
                    <b>Product</b>
                </th>
                <th>
                    <b>Amount</b>
                </th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    Kroket
                </td>
                <td>
                    € 5.00 <!-- Dynamically generated -->
                </td>
            </tr>
        </tbody>
        <tfoot>
          <tr>
            <td>Total:</td>
            <td class="total"></td>
        </tr>
    </tfoot>
</table>

因此,在这个页面上是一个按日期排序的表格列表,我想显示其总额。

我希望这个总额显示在class="total"的td元素中。为此,我尝试使用以下JQuery函数:

function updateTotalOfTotals() {
    $(".table").each(function () {
        var totalSum = 0;
        var $dataRow = $('table tbody tr');
        $dataRow.each(function () {
            // In reality I have some more td elements and the amounts 
            // are in the 4th column.
            $(this).find('td:nth-child(4)').each(function (i) {
                totalSum += parseFloat($(this).text().replace("€", ""));
            });
        });
        var twoPlacedFloatTotalSum = parseFloat(totalSum).toFixed(2);
        $(".total").each(function (i) {
            $(this).html(twoPlacedFloatTotalSum);
        });
    });
}

当我只有一张表时,类似的函数也会起作用。但在这里,我无法让它工作,因为它显示了每个表中所有表的总数。无论如何,我都不是JavaScript/JQuery方面的专家,如果有人能为我提供更多见解,我将不胜感激。

function updateTotalOfTotals() {
    $(".table").each(function () {
        var totalSum = 0;
        //target only the trs from current table
        var $dataRow = $(this).find('tbody tr');
        $dataRow.each(function () {
            $(this).find('td:nth-child(2)').each(function (i) {
                totalSum += parseFloat($(this).text().replace("€", ""));
            });
        });
        var twoPlacedFloatTotalSum = parseFloat(totalSum).toFixed(2);
        //target only the total from current table
        $(this).find(".total").html(twoPlacedFloatTotalSum);
    });
}

演示:Fiddle