我对你的代码做了一些修改。好像现在起作用了。主要的更改是只重新计算已更改的行,而不是每次都重新计算每一行。当然,总数仍然是从所有总数中计算出来的。我还使用了事件委托来最小化绑定事件处理程序,这将对大型表的性能和资源使用产生影响。
jQuery(
function($)
{
// threshold that defines at what quantity to use the discounted price
var discountThreshold = 10;
// bind the recalc function to the quantity fields
// use event delegation to improve performance
$("#frmOrder")
.delegate(
"input[name^=qty_item_]",
"keyup",
recalc
);
// run the calculation function once on every quantity input
$("input[name^=qty_item_]").trigger("keyup");
// recalculate only the changed row (and the grand total)
function recalc(e) {
// input field that triggered recalc()
var
$this = $(this),
$parentRow = $this.closest('tr'),
quantity = $this.parseNumber()[0],
$usePrice = ((discountThreshold <= quantity) ? $("[id^=price_item_2_]", $parentRow) : $("[id^=price_item_1_]", $parentRow)) || 0;
// recalculate the row price
$("[id^=total_item_]", $parentRow).calc(
// the equation to use for the calculation
"qty * price",
// define the variables used in the equation, these can be a jQuery object
{
qty: $this,
price: $usePrice
},
// define the formatting callback, the results of the calculation are passed to this function
function (s){
// return the number as a dollar amount
return "$" + s.toFixed(2);
},
// define the finish callback, this runs after the calculation has been complete
function ($that){
// sum the total of the $("[id^=total_item]") selector
var sum = $("[id^=total_item_]").sum();
$("#grand_total").text(
// round the results to 2 digits
"$" + sum.toFixed(2)
);
}
);
}
}
);