2013-11-26 31 views
0

我有一個頁面,每個日期都有動態生成的表格。每個日期都有一列顯示每件產品的付款金額。例如,如何獲得每個動態生成的表格的總和?

<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元素中,class =「total」。爲此,我嘗試使用以下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的專家,如果有人能夠提供給我更多的見解,我將非常感激。

+1

'變量$的DataRow = $(本).find( 'TBODY TR');'和'$(本).find( '總')HTML(twoPlacedFloatTotalSum );' –

+1

'$(「。total」)。each(function(i){'必須改爲只針對一個'total'元素 – Abhitalks

+0

謝謝我現在得到它!:) –

回答

3
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

+0

Works!驚人。 –

+2

@ user2609980:除了工作答案(+1)之外,我可能會考慮添加實際的數值和貨幣(如果需要的話)作爲數據屬性添加到'td',即:€5.00​​'這樣你就可以簡化代碼,而不必擔心貨幣符號。這也意味着您在符號更改時不必更新解析代碼。也允許你有更多的貨幣轉換靈活性等。 – Nope

+0

@FrançoisWahl是的,你是對的...否則格式化可能會導致解析值的問題 –