如何修复JavaScript中多选checkbox选中值累加求和失效的问题
问题修复方案
核心故障原因
- 你使用了
if...else if连锁判断逻辑,该结构只要命中任意一个符合条件的判断,就会跳过后续所有判断逻辑,因此仅能收集到第一个勾选项的卡路里值 - 你使用了表单默认的submit按钮,点击后会触发页面提交刷新,会导致计算结果未展示就被页面重置
修复后代码
JavaScript代码
var rice = 204; var bread = 140; var chicken = 147; var beef = 282; var carrots = 150; var beans = 70; // 接收事件参数用于阻止默认提交行为 function myFunction(e) { // 阻止表单默认提交刷新页面的行为 e.preventDefault(); var rice = document.getElementById("rice"); var bread = document.getElementById("bread"); var chicken = document.getElementById("chicken"); var beef = document.getElementById("beef"); var carrots = document.getElementById("carrots"); var beans = document.getElementById("beans"); const food = []; // 把所有else if改为独立if判断,每个勾选项都单独校验 if (rice.checked == true) { food.push(window.rice); } if (bread.checked == true) { food.push(window.bread); } if (chicken.checked == true) { food.push(window.chicken); } if (beef.checked == true) { food.push(window.beef); } if (carrots.checked == true) { food.push(window.carrots); } if (beans.checked == true) { food.push(window.beans); } let sum = food.reduce(function(a, b) { return a + b; }, 0); // 弹窗展示总卡路里 alert(`总卡路里:${sum}`); console.log(sum); console.log(food); }
HTML代码(仅修改提交按钮部分)
<!-- 点击时把事件对象传入函数 --> <input type="submit" onclick="myFunction(event)" />
可选优化方案
你可以用对象统一存储食物和对应卡路里数值,无需写大量重复的判断代码,后续新增食物仅需修改对象即可:
const calorieMap = { rice: 204, bread: 140, chicken: 147, beef: 282, carrots: 150, beans: 70 } function myFunction(e) { e.preventDefault() let totalCalorie = 0 // 遍历对象自动校验所有勾选项 Object.keys(calorieMap).forEach(foodId => { if (document.getElementById(foodId).checked) { totalCalorie += calorieMap[foodId] } }) alert(`总卡路里为:${totalCalorie}`) }
内容的提问来源于stack exchange,提问作者User617290653251457439
相关产品推荐
相关产品推荐

