如何改写JavaScript脚本以同时自动计算总价与总成本?
需求与解决方案
现有以下JavaScript脚本和HTML表单,当前仅能计算总价(Total Price),需要改写脚本实现:输入Quantity(数量)、Unit Price(单价)、Unit Cost(单位成本)时,同时自动计算Total Price(总价)与Total Cost(总成本)。
修改后的代码
JavaScript部分
function calc() { // 获取所有输入值,转为数字,空值或非数字默认取0 const quantity = Number(document.getElementById('quantity').value) || 0; const unitPrice = Number(document.getElementById('unit_price').value) || 0; const unitCost = Number(document.getElementById('unit_cost').value) || 0; // 计算总价和总成本 const totalPrice = quantity * unitPrice; const totalCost = quantity * unitCost; // 更新对应输入框的值 document.getElementById('sub_price').value = totalPrice; document.getElementById('sub_cost').value = totalCost; }
HTML部分
<form> Quantity: <input type="number" id="quantity" name="quantity" value="1" onkeyup="calc()" required="required"/> <br> Unit Price:<input type="number" id="unit_price" onkeyup="calc()" name="unit_price" step="any" value="3" required="required" /> <br> Total Price:<input type="number" id="sub_price" name="sub_price" step="any" value="" readonly required="required" /> <br><br> Unit Cost:<input type="number" id="unit_cost" onkeyup="calc()" name="unit_cost" step="any" value="2" required="required" /> <br> Total Cost:<input type="number" id="sub_cost" name="sub_cost" step="any" value="" readonly required="required" /> </form>
改动说明
- 简化
calc函数逻辑,不再判断触发元素,直接获取所有需要的输入值,避免分支冗余 - 新增单位成本的取值与总成本的计算逻辑
- 移除原脚本中无对应DOM元素的
update节点操作,避免控制台报错 - 所有输入框的
onkeyup事件统一调用calc(),确保任意输入变化都能同步更新两个计算结果
内容的提问来源于stack exchange,提问作者CPY Business Centre 澤昇商務中心
相关产品推荐
相关产品推荐

