[英]How can I get the sum of a colum for each dynamically generated table?
我有一個頁面,每個日期都有動態生成的表格。 每個日期都有一個列,顯示每件產品的付款金額。 例如,
<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>
因此,此頁面上是按日期排序的表的列表,我要顯示其總額。
我希望此總金額顯示在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);
});
}
演示: 小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.