javascript - 通过 Jquery 在动态 HTML 表的单元格中执行计算
问题描述
我基本上是在动态表格单元格中执行计算想要在用户更改单元格值时更改单元格值的总和
我已经尝试过不同的 jquery 方法,但没有得到我想要的
<table class="table table-responsive table-hover table-bordered" id="tablefinaldata">
<thead>
<tr>
<td>
<h5> Code</h5>
</td>
<td>
<h5> Item</h5>
</td>
<td>
<h5> Price</h5>
</td>
<td>
<h5> Quantity</h5>
</td>
<td>
<h5> Sub Total</h5>
</td>
</tr>
</thead>
<tbody id="tablefinalbody">
</tbody>
function CalSum ()
{
$("#setfinaldata #subtotal").each(function () {
var row = $(this);
var rowTotal = 0;
$(this).find('th').each(function () {
var th = $(this);
if ($.isNumeric(th.text())) {
rowTotal += parseFloat(th.text());
}
});
row.find('th:last').text(rowTotal);
});
}
解决方案
function CalSum() {
var $trList = $("#tablefinalbody").find('tr');
var rowTotal = new Array($trList.length);
$trList.each(function() {
var row = $(this);
$(this).find('th').each(function(index) {
var th = $(this);
if ($.isNumeric(th.text())) {
if (!rowTotal[index]) rowTotal[index] = 0
rowTotal[index] += parseFloat(th.text());
}
});
});
$trList.last().children().each(function(index) {
$(this).text(rowTotal[index])
})
}
CalSum();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-responsive table-hover table-bordered" id="tablefinaldata">
<thead>
<tr>
<td>
<h5> Code</h5>
</td>
<td>
<h5> Item</h5>
</td>
<td>
<h5> Price</h5>
</td>
<td>
<h5> Quantity</h5>
</td>
<td>
<h5> Sub Total</h5>
</td>
</tr>
</thead>
<tbody id="tablefinalbody">
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
<tr>
<th>123</th>
<th>42</th>
<th>53</th>
<th>64</th>
<th>234</th>
</tr>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tbody>
</table>
推荐阅读
- angular - kendo-toolbar-dropdownbutton 在 kendoGridToolbarTemplate Angular 7 中不起作用
- python - 通过索引检索二维数组元素的Pythonic方法
- django - 使用通用列表视图从用户模型中获取用户的成员资格列表
- python - 使用 .grid() 时配置滚动条高度
- python - 在python中读取和提取条目
- linux - 使用脚本将文件从 Linux 复制到 Windows
- java - 我正在尝试编写查找和替换 Java 程序
- flowtype - 键入的未密封对象不允许使用新道具
- random - 如何使文本在一定时间后自动更改?
- php - 使用 tld 之后的所有内容重定向 URL