如何在条件语句中区分目标值、空值及非目标值?附下拉选框案例
解决Select未选择状态与非美国状态区分的问题
问题核心:当前代码中,未选择任何国家时(默认选项"Select Country"),其值不等于"United States",会被归类到非美国的逻辑分支里,无法触发单独的未选择操作。
修改方案
- 优化默认选项值:将默认option的value设为空字符串,更清晰标识未选择状态
- 调整条件判断顺序:优先判断未选择国家的情况,避免被其他条件覆盖
- 简化逻辑分支:确保未选择时无论复选框状态如何,都执行隐藏所有内容的操作
修改后的代码
JavaScript
var selectedCountry, selectAutograph $('.country, .autograph').on('change', function() { selectedCountry = $('.country').find('option:selected').val(); selectAutograph = $('.autograph').is(":checked") // 先判断未选择国家的情况 if (!selectedCountry) { console.log("Show Nothing"); $(".intauto, .usauto, .us, .int").hide(); } else if (selectedCountry === "United States" && !selectAutograph) { console.log("Show US Only"); $(".us").show(); $(".int, .intauto, .usauto").hide(); } else if (selectedCountry !== "United States" && !selectAutograph) { console.log("Show Int Only"); $(".int").show(); $(".us, .intauto, .usauto").hide(); } else if (selectedCountry === "United States" && selectAutograph) { console.log("Show US and Autograph"); $(".usauto").show(); $(".intauto, .us, .int").hide(); } else if (selectedCountry !== "United States" && selectAutograph) { console.log("Show Int and Autograph"); $(".intauto").show(); $(".usauto, .us, .int").hide(); } });
HTML
<form id="order-form" method="post" role="form"> <select class="country" name="country" id="country"> <!-- 将默认选项value设为空字符串 --> <option value="">Select Country</option> <option value="United States">United States</option> <option value="Canada">Canada</option> <option value="United Kingdom">United Kingdom</option> <!-- ... --> <option value="Zimbabwe">Zimbabwe</option> </select> <div class="form-check"> <input class="autograph" type="checkbox" value="" id="autograph" name="autograph"> <label class="form-check-label"> Add autograph </label> </div> </form> <div> <div class="us hide"> US shipping </div> <div class="int hide"> International shipping </div> <div class="usauto hide"> US shipping + add autograph </div> <div class="intauto hide"> International shipping + add autograph </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CSS
.hide { display: none; }
关键说明
- 默认选项value设为空后,
!selectedCountry可以准确判断未选择状态 - 将未选择的判断放在最前面,确保不会被后续的
!== "United States"条件覆盖 - 所有分支逻辑清晰,每个状态对应明确的显示/隐藏操作
内容的提问来源于stack exchange,提问作者LOTUSMS
相关产品推荐
相关产品推荐

