项目需求要根据金额的大小动态列出审批者,当金额发生变动时去执行异步请求,现在的问题是无论是我改金额或是数量都会计算金额并执行异步请求,
每一次的单价或者数量的变化(计算合计金额)都会执行异步请求,很消耗资源
有什么好的优化方案呢?
这是js代码:
<script>
// 监听单价和数量的变化
$(document).on('input propertychange', '.cg-items-table tbody input.listen', function (e) {
var tr = $(this).parent().parent(),
unitPrice = parseFloat(tr.find('td:nth-child(5) input').val()),
quantity = parseFloat(tr.find('td:nth-child(6) input').val()),
amount = ((unitPrice ? unitPrice : 0) * (quantity ? quantity : 1));
tr.find('td:nth-child(8) input').val(amount.toFixed(2));
amountCalculation();
});
// 计算合计金额并执行异步请求
function amountCalculation() {
var totalAmount = 0;
// 填充行合计
$('.cg-items-table tbody tr').each(function (index) {
totalAmount += parseFloat($(this).find('.amount').val());
});
// 总金额赋值
$('.cg-items-table tfoot tr td:last-child input').val(totalAmount.toFixed(2));
getReviewers({
totalAmount: totalAmount
});
}
</script>
去搜索下函数节流。