编程新手求助:点击Calculate按钮后脚本无法显示供应商总价
问题排查与修复
问题描述
我是编程新手,点击Calculate按钮后,脚本无法显示不同供应商的总价,希望帮忙排查代码错误(我有consumption.json和providers.json两个数据文件,认为问题不在JSON文件上)。
相关代码
index.html
<!DOCTYPE html> <html> <head> <title>Energy Consumption Calculator</title> </head> <body> <h1>Energy Consumption Calculator</h1> <form id="calculation-form"> <div> <label for="fixedPrice">Fixed Price:</label> <input type="number" id="fixedPrice" name="fixedPrice"> </div> <div> <label for="variablePrice">Variable Price:</label> <input type="number" id="variablePrice" name="variablePrice"> </div> <div> <label for="spotPrice">Spot Price:</label> <input type="number" id="spotPrice" name="spotPrice"> </div> <button type="submit">Calculate</button> </form> <div id="output"></div> </body> </html>
app.js
async function getData(url) { const response = await fetch(url); return response.json(); } async function calculatePrice() { const consumptionData = await getData("consumption.json"); const providersData = await getData("providers.json"); const prices = []; // 读取输入值并处理空值情况 const fixedPrice = parseFloat(document.getElementById("fixedPrice").value) || 0; const variablePrice = parseFloat(document.getElementById("variablePrice").value) || 0; const spotPrice = parseFloat(document.getElementById("spotPrice").value) || 0; // 遍历每个供应商单独计算总价 for (const provider of providersData) { let total = 0; for (const consumption of consumptionData) { switch(provider.pricingModel) { case "fixed": total += fixedPrice * consumption.consumption; break; case "variable": total += variablePrice * consumption.consumption; break; case "hourlySpot": // 与providers.json中的定价模型字段对应 total += spotPrice * consumption.consumption; break; case "monthlySpot": // 区分不同类型的spot定价 total += spotPrice * consumption.consumption; break; } } prices.push({ provider: provider.name, totalPrice: total.toFixed(2) }); } // 生成输出内容 let output = "<ul>"; for (const price of prices) { output += `<li>${price.provider}: ${price.totalPrice}</li>`; } output += "</ul>"; document.getElementById("output").innerHTML = output; } const form = document.getElementById("calculation-form"); form.addEventListener("submit", function (event) { event.preventDefault(); calculatePrice(); });
核心错误点与修复说明
- 重复条件分支:原代码中有两个完全相同的
else if (provider.pricingModel === "spotPrice"),第二个分支永远无法触发,导致对应供应商总价始终为0。改用switch结构并区分不同spot定价类型(需与providers.json中的字段匹配)。 - 硬编码供应商名称:原代码手动指定供应商名称,若providers.json中供应商信息变化,结果会不匹配。修复后直接从数据源读取供应商名称。
- 变量未重置:原代码中总价变量未在每次调用函数时重置,多次点击按钮会累加历史结果。修复后改为每个供应商单独计算总价,避免全局累加。
- 输入值未校验:原代码未处理输入为空的情况,会导致
parseFloat返回NaN,最终总价失效。添加|| 0确保空值转为0。 - 冗余事件绑定:原按钮同时绑定了
onclick和表单submit事件,移除onclick避免重复触发函数。
内容的提问来源于stack exchange,提问作者mariusep
相关产品推荐
相关产品推荐

