遇到这样一个场景,我需要对我的输出数据表,添加一个求和的功能。在后台加逻辑写求和是比较麻烦的。然后,就想到了通过js实现。这样在网络上找到一个Demo。这里也把这个东西分享一下。
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Jquery计算table行合计</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body style="width:100%; height:100%;">
<table id="mytable" border="1" width="37%">
<thead>
<tr>
<td width="63">ID</td>
<td width="68">字段1</td>
<td width="62">字段2</td>
<td width="75">字段3</td>
<td>字段4</td>
</tr>
</thead>
<tbody>
<tr>
<td>項目1 </td>
<td width="63">11</td>
<td width="68">12</td>
<td width="62">13</td>
<td width="75">14</td>
</tr>
<tr>
<td>項目2</td>
<td width="63">22</td>
<td width="68">26</td>
<td width="62">28</td>
<td width="75">27</td>
</tr>
</tbody>
<tfoot>
<tr id="totalRow">
<td>合计</td>
<td width="63"></td>
<td width="68"></td>
<td width="62"></td>
<td width="75"></td>
</tr>
</tfoot>
</table>
<script>
var sum = new Array(+$('#mytable thead tr td:not(:first-child)').length).fill(0);
$('#mytable tbody tr').each(function () {
$(this).children('td:not(:first-child)').each(function () {
var index = $(this).index() - 1;
sum[index] += +$(this).text();
});
});
$('#mytable #totalRow td:not(:first-child)').each(function () {
var index = $(this).index() - 1;
$(this).text(sum[index]);
});
</script>
</body>
</html>
网友评论