实现Switch与Currency联动验证以显示正确定价的技术求助
解决方案
你的代码存在两个核心问题:
- Switch组件未绑定任何事件监听,切换状态时不会触发价格更新逻辑
- 每个货币按钮的点击事件里重复编写开关判断逻辑,且没有记录当前选中的货币,导致开关变化时无法匹配对应货币的价格
直接重构代码,用统一的数据结构存储价格,同时监听开关和货币按钮的变化,触发同一个价格更新函数即可解决问题:
重构后的代码
HTML(保留原结构,给货币按钮统一类名方便监听)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label class="switch"> <input id="mycheckbox" name="checkbox" type="checkbox"> <span class="slider round"></span> </label> <button id="usdBtn" class="currency-btn active">USD</button> <button id="eurBtn" class="currency-btn">EUR</button> <button id="gbpBtn" class="currency-btn">GBP</button> <div id="start-price">$20</div> <div id="mid-price">$30</div>
CSS(保留原Switch样式,新增激活状态样式可选)
/* 原Switch样式保留 */ .switch { position: relative; display: inline-block; width: 60px; height: 34px; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: .4s; transition: .4s; } input:checked + .slider { background-color: #2196F3; } input:focus + .slider { box-shadow: 0 0 1px #2196F3; } input:checked + .slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); } .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; } /* 可选:给选中的货币按钮加激活样式,提升用户体验 */ .currency-btn.active { background-color: #2196F3; color: white; }
JavaScript(核心重构部分)
$(document).ready(function () { // 用对象统一存储所有价格数据,后续调整价格/新增货币只需修改这里 const priceData = { USD: { annual: { start: "$20", mid: "$30" }, monthly: { start: "$25", mid: "$40" } }, EUR: { annual: { start: "€25", mid: "€35" }, monthly: { start: "€30", mid: "€40" } }, GBP: { annual: { start: "£40", mid: "£50" }, monthly: { start: "£45", mid: "£50" } } }; // 记录当前选中的货币,默认初始为USD let currentCurrency = "USD"; // 统一的价格更新函数,根据当前状态渲染对应价格 function updatePrices() { const isMonthly = $('#mycheckbox').is(':checked'); const period = isMonthly ? 'monthly' : 'annual'; const targetPrices = priceData[currentCurrency][period]; $('#start-price').text(targetPrices.start); $('#mid-price').text(targetPrices.mid); } // 货币按钮点击事件处理 $('.currency-btn').click(function() { currentCurrency = $(this).attr('id').replace('Btn', ''); // 切换按钮激活状态(可选) $('.currency-btn').removeClass('active'); $(this).addClass('active'); // 更新价格 updatePrices(); }); // Switch组件状态变化事件监听 $('#mycheckbox').on('change', updatePrices); });
重构优势
- 数据驱动:所有价格集中存储,后续维护只需修改数据对象,无需改动逻辑代码
- 单一职责:
updatePrices函数专门负责价格渲染,所有交互事件都调用它,避免重复逻辑 - 状态跟踪:用变量记录当前选中的货币,开关切换时能直接匹配对应价格
- 代码简洁:删除了大量重复的价格设置函数,减少冗余代码
内容的提问来源于stack exchange,提问作者Robin
相关产品推荐
相关产品推荐

