复选框联动价格逻辑开发需求:首选不调价,后续每选加价0.10
复选框联动价格的实现方案
HTML 结构
先搭建基础的复选组和价格展示元素:
<!-- 复选框组 --> <div class="checkbox-group"> <label><input type="checkbox" class="price-checkbox" data-increment="0"> 选项1(不影响价格)</label> <label><input type="checkbox" class="price-checkbox" data-increment="0.1"> 选项2</label> <label><input type="checkbox" class="price-checkbox" data-increment="0.1"> 选项3</label> <label><input type="checkbox" class="price-checkbox" data-increment="0.1"> 选项4</label> </div> <!-- 价格展示区域 --> <div>当前价格:<span id="current-price">10.00</span> 元</div>
JavaScript 逻辑
通过监听复选框状态变化,实时计算并更新价格:
// 初始化核心参数 const initialPrice = 10.00; // 初始价格,可根据需求修改 const priceDisplay = document.getElementById('current-price'); const checkboxes = document.querySelectorAll('.price-checkbox'); // 价格更新函数 function calculatePrice() { let totalPrice = initialPrice; let checkedNum = 0; checkboxes.forEach(box => { if (box.checked) { checkedNum++; // 累加对应复选框的价格增量 totalPrice += parseFloat(box.dataset.increment); } }); // 全未选中时重置为初始价格 if (checkedNum === 0) { totalPrice = initialPrice; } // 格式化价格为两位小数,避免浮点数精度问题 priceDisplay.textContent = totalPrice.toFixed(2); } // 给每个复选框绑定状态变化事件 checkboxes.forEach(box => { box.addEventListener('change', calculatePrice); });
关键逻辑说明
- 用
data-increment属性给每个复选框标记价格增量:第一个设为0,后续设为0.1,后续新增选项只需修改属性值,无需改动核心逻辑 - 每次复选框状态改变时,遍历所有复选框累加选中项的增量
- 无选中项时强制重置为初始价格
- 用
toFixed(2)保证价格始终显示两位小数,解决浮点数运算的精度误差
内容的提问来源于stack exchange,提问作者Wakil Ahmed
相关产品推荐
相关产品推荐

