javascript - 在jquery中唯一地计算表的每一行
问题描述
我正在开发 POS 系统。在这里,我需要唯一地计算每个项目的总数。我写了一个 onKeyUp 函数来计算金额。它非常适合单排。如果我修改为第二个产品添加了折扣 2,它会影响第一行。
HTML:
<table class="table table-striped table-hover" id="item_table">
<thead id="thead">
<tr class="bg-primary">
<th>#</th>
<th>Product Name</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Discount</th>
<th>Discount 2</th>
<th>Amount</th>
<th><i class="fa fa-close"></i></th>
</tr>
</thead>
<tbody id="item_list">
<tr>
<td><?php echo $n; ?></td>
<td><?php echo $product_name; ?></td>
<td><input type="number" class="form-control" name="quantity[]" id="quantity" value="1" min="1" step="1"></td>
<td id="sprice"><?php echo $selling_price; ?></td>
<td id="discount"><?php echo $discount_rate; ?>%</td>
<td><input type="text" class="form-control" name="discount2" id="discount2"></td>
<td id="total"><?php echo number_format($total,2,'.', ''); ?></td>
<td><span><i class="fa fa-trash"></i></span></td>
</tr>
</tbody>
</table>
这里使用的 PHP 代码第一次将行插入到表中。这没有问题。它与一个记录一起工作。
JavaScript:
//Product Row Calculation
function calculateItemPrice() {
var sprice = $("#item_table #sprice").text();
var quantity = $("#item_table #item_list #quantity").val();
var discount = $("#item_table #discount").text().slice(0, -1);
var discount2 = $("#item_table #item_list #discount2").val();
$('tr').each(function() {
var totalDiscount = ((sprice * quantity) * discount / 100);
var price = ((((sprice * quantity) - totalDiscount)) - discount2);
var total = parseFloat(price).toFixed(2);
$("#total").html(total);
});
}
$("#item_table").on("keyup", "#quantity", function() {
calculateItemPrice();
});
$("#item_table").on("keyup", "#discount2", function() {
calculateItemPrice();
});
解决方案
试试这样:
//Product Row Calculation
function calculateItemPrice(sprice,quantity,discount,discount2){
var totalDiscount = ((sprice * quantity) * discount/100);
var price = ((((sprice * quantity) - totalDiscount))- discount2);
var total = parseFloat(price).toFixed(2);
//alert("Hi");
return total;
}
$("#item_table").on("keyup","#discount2 , #quantity", function() {
var sprice = $(this).closest('tr').find("#sprice").text();
var quantity = $(this).closest('tr').find("#quantity").val();
var discount = $(this).closest('tr').find("#discount").text().slice(0,-1);
var discount2 = $(this).closest('tr').find("#discount2").val();
total2 = calculateItemPrice(sprice,quantity,discount,discount2);
$(this).closest('tr').find('#total').html(total2);
//alert(discount2);
});
推荐阅读
- javascript - 为什么我在使用这个关键字时变得不确定
- java - 有没有办法使用java从本地系统上传文件到EFS?
- c# - .Net Core webApi 在运行时将属性添加到传入的 Dto
- git - 如何在格式化的 git 提交日期输出上将时区更改为本地?
- node.js - FLUTTER - Cloud Functions Firestore 查询在我使用数组时返回 0 个结果,但在我使用字符串时返回一些结果
- javascript - Angular 项目:Hibernate 不会自动创建表
- python-3.x - 可以使用 tracemalloc 来分析用 python 2.x 编写的应用程序吗?
- regex - 如何在 grep 中为 MINGW64 使用方括号?
- sql-server-2016 - 加入 2 个表,匹配两个表中的 2 列
- python - 扩大二维阵列掩模中的孔