You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现按数量调整单价的JavaScript价格计算器?

问题分析与修正代码

你的代码存在几个关键问题:

  • 判断条件错误:应该检查购买数量qty是否大于1000,而非总金额result
  • toFixed(2)会将数字转为字符串,提前使用会导致后续计算出错,应在所有计算完成后再格式化小数
  • 折扣计算语法错误:JS中不能直接写10%,需用* 0.9等价于减去10%金额的方式实现
  • 函数参数price未被使用,调用时传入qty*2属于多余操作

以下是两种符合需求的实现方案,任选其一即可:

方案1:数量超1000时单价改为1.8

function calculate() {
  // 获取数量并转为数字,空值/非数字默认设为0
  let qty = parseFloat(document.getElementById("qty").value) || 0;
  // 根据数量判断单价
  let unitPrice = qty > 1000 ? 1.8 : 2;
  // 计算总金额后保留两位小数
  let result = (qty * unitPrice).toFixed(2);
  document.getElementById("result").value = result;
}

方案2:数量超1000时享受10%折扣

function calculate() {
  let qty = parseFloat(document.getElementById("qty").value) || 0;
  let total = qty * 2;
  // 数量超过1000则打9折
  if (qty > 1000) {
    total = total * 0.9;
  }
  document.getElementById("result").value = total.toFixed(2);
}

修正后的HTML

调用函数时无需传参,直接执行calculate()即可:

<form role="form" id="price" name="price">
  <p>
    <input type="text" id="qty" onchange="calculate()" value="">
  </p>
  <p>
    <input type="text" id="result" value="" disabled>
  </p>
</form>

内容的提问来源于stack exchange,提问作者Dontheman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:40:36