带嵌套if语句的单选按钮定价计算器开发问题求助
解决定价计算器中Radio按钮值的计算问题
你的代码主要有三个问题导致逻辑失效:
- 计算出的
cateringFunc完全没用到,反而把catering的原值重复push到数组,totalPrice也只加了原值 - 获取
gastronomy的add-value时,没有选中当前已勾选的项,而是直接取了页面中第一个name="gastronomy"元素的属性 - 内层if执行后没有跳过外层的默认逻辑,导致重复添加值
下面是修正后的代码:
修正后的JavaScript
$(".w-radio").change(function() { let totalPrice = 0; const values = []; // 获取已选中的gastronomy的add-value,转成数字,默认值设为1避免NaN const gastronomyAddValue = parseInt($('input[name="gastronomy"]:checked').attr('data-add-value')) || 1; // 只遍历已勾选的radio,减少无效循环 $("input[type=radio]:checked").each(function() { const $radio = $(this); const radioValue = parseInt($radio.val()); if ($radio.is('[name="catering"]')) { // 计算catering的最终值并加入数组和总价 const cateringFinalValue = radioValue * gastronomyAddValue; values.push(cateringFinalValue); totalPrice += cateringFinalValue; } else { // 其他radio直接使用原值 values.push(radioValue); totalPrice += radioValue; } }); $("#priceTotal span").text(totalPrice); // 可选:打印数组查看结果 console.log(values); });
修正后的HTML(规范自定义属性)
建议把自定义属性add-value改成data-add-value,符合HTML5自定义属性的规范:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label class="hack43-radio-group w-radio"> <input type="radio" name="gastronomy" value="0" data-add-value="10">0<BR> <input type="radio" name="gastronomy" value="550" data-add-value="10">550<BR> <input type="radio" name="gastronomy" value="550" data-add-value="10">550<BR> <input type="radio" name="gastronomy" value="550" data-add-value="10">550<BR> </label> <br> <label class="hack43-radio-group w-radio"> <input type="radio" name="venue" value="0">0<BR> <input type="radio" name="venue" value="10500">10500<BR> <input type="radio" name="venue" value="10500">10500<BR> <input type="radio" name="venue" value="10500">10500<BR> </label> <br> <label class="hack43-radio-group w-radio"> <input type="radio" name="catering" value="0">0<BR> <input type="radio" name="catering" value="40">40<BR> <input type="radio" name="catering" value="45">45<BR> <input type="radio" name="catering" value="60">60<BR> </label> <div class="hack42-45-added-value-row"> <div id="priceTotal"> <span>0</span> </div> </div>
关键修正点说明:
- 先获取已选中的gastronomy的
data-add-value,确保用的是当前选择的配置 - 遍历的时候直接处理已勾选的radio,减少不必要的循环
- 对catering单独处理计算逻辑,其他radio走默认逻辑,避免重复添加值
- 统一把字符串转成数字再计算,避免隐式类型转换的问题
- 用
data-add-value替代自定义的add-value,符合HTML标准
内容的提问来源于stack exchange,提问作者Jeff
相关产品推荐
相关产品推荐

