利用Jquery选择器,计算table中的某一列,某一行的合计,非常方便。下面以计算行合计为例:
核心算法:
view sourceprint?1 $('#tableId tr').each(function() {
2 $(this).find('td:eq(columnIndex)').each(function() {
3 totalAmount += parseFloat($(this).text());
4 })
5 });
下面是案例代码
view sourceprint?01 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02 <html xmlns="http://www.w3.org/1999/xhtml">
03 <head>
04 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
05 <title>Jquery计算table行合计</title>
06 <script id="jquery_183" type="text/javascript" class="library" src="http://runjs.cn/js/sandbox/jquery/jquery-1.8.3.min.js"></script>
07 <script type="text/javascript">
08 $(document).ready(function() {
09
10 var totalRow = 0
11 $('#mytable tr').each(function() {
12 $(this).find('td:eq(2)').each(function(){
13 totalRow += parseFloat($(this).text());
14 });
15 });
16
17 $('#totalRow').append('<td>合计</td><td></td><td>'+totalRow+'</td><td></td>');
18 });
19 </script>
20
21 </head>
22 <body style="width:100%; height:100%;">
23 <table id="mytable" border="1" width="37%">
24 <thead>
25 </thead>
26 <tr>
27 <td width="63" >11</td>
28 <td width="68" >12</td>
29 <td width="62" >13</td>
30 <td width="75" >14</td>
31 </tr>
32 <tr>
33 <td width="63" >21</td>
34 <td width="68" >22</td>
35 <td width="62" >23</td>
36 <td width="75" >24</td>
37 </tr>
38 <tr id="totalRow"></tr>
39 </table>
40 </body>
41 </html>
效果图:
更多信息请查看IT技术专栏