嗨我发现以下JavaScript代码没有采用当前的GrossTotal()值,直到我重写Quantity或UnitPrice值
$(document).ready(function () {
$("[id*=gridpur]input[type=text][id*=txtCalc]").on('keyup', (function (e) {
var unitprice = $(this).closest('tr').find("input[type=text][id*=txtCalcUnitprice]").val();
var quantity = $(e.target).closest('tr').find("input[type=text][id*=txtCalcQuantity]").val();
var total = unitprice * quantity;
var cost = (total / GrossTotal())*100;
$(e.target).closest('tr').find("[id*=lblTotal]").text(total);
$(e.target).closest('tr').find("[id*=lblcost]").text(cost);
}));
});
var gross;
function GrossTotal() {
gross = 0;
$("[id*=gridpur][id*=lblTotal]").each(function (index, item) {
gross = gross + parseInt($(item).text());
});
$("[id*=lblGrandTotal]").text(gross);
return gross;
}
例如,如果输入了以下值,则输出哪个不正确
ProductName UnitPrice Quantity Amount Cost %
product1 9 1 9 Infinity
product2 9 1 9 100
product3 9 1 9 50
我只在重写Quantity或UnitPrice
后得到正确的值ProductName UnitPrice Quantity Amount Cost %
product1 9 1 9 33.3
product2 9 1 9 33.3
product3 9 1 9 33.3
答案 0 :(得分:0)
确保在从输入中读取值时将它们默认为0。在分割之前检查0
unitprice = !isNaN(unitprice) ? 0 : unitprice;
quantity = !isNaN(quantity) ? 0 : quantity;
var total = unitprice * quantity;
var grossTotal = GrossTotal(),
cost = 0;
if(grossTotal > 0) {
cost = (total / grossTotal) *100;
}
使用parseInt
parseInt($(item).text(), 10)
答案 1 :(得分:0)
问题是,GrossTotal()
会将所有lblTotal
字段中的值相加,但是在您调用 之后才会填写它们。改变这些行:
var cost = (total / GrossTotal())*100;
$(e.target).closest('tr').find("[id*=lblTotal]").text(total);
$(e.target).closest('tr').find("[id*=lblcost]").text(cost);
为:
$(e.target).closest('tr').find("[id*=lblTotal]").text(total);
var cost = (total / GrossTotal())*100;
$(e.target).closest('tr').find("[id*=lblcost]").text(cost);