如何用jQuery动态控制Select选项的显示与隐藏(特定场景需求)
解决方案:根据Location选择动态控制Restaurant下拉框的RR选项
你的核心问题是直接移除RR选项后无法恢复——DOM元素被删除后无法直接找回。正确的做法是先缓存RR选项,再根据选中的Location值动态添加或移除它。
修改后的JavaScript代码
// 页面加载时缓存RR选项,避免移除后无法恢复 const rrOption = $('#restaurant option[value="RR"]').clone(); $('#location').on('change', function () { const locationValue = $(this).val(); const $restaurant = $('#restaurant'); const $restaurantSelect = $('#restaurantSelect'); if (locationValue === "PF II" || locationValue === "PF II-extensão") { // 启用并显示餐厅选择框 $restaurant.removeAttr('disabled'); $restaurantSelect.show(); $restaurant.val(""); if (locationValue === "PF II-extensão") { // 移除RR选项 $restaurant.find('option[value="RR"]').remove(); } else if (locationValue === "PF II") { // 检查RR选项是否存在,不存在则添加回去 if (!$restaurant.find('option[value="RR"]').length) { $restaurant.append(rrOption.clone()); } } } else { // 禁用并隐藏餐厅选择框,重置选中值 $restaurant.attr('disabled', 'disabled'); $restaurantSelect.hide(); $restaurant.val("A"); // 确保隐藏时RR选项已恢复,避免下次切换到PF II时出错 if (!$restaurant.find('option[value="RR"]').length) { $restaurant.append(rrOption.clone()); } } })
代码说明
- 缓存RR选项:页面加载时克隆一份RR选项保存,这样即使DOM中的RR被移除,我们还有备份可以重新添加。
- 分场景处理:
- 选中
PF II-extensão时,直接移除DOM中的RR选项 - 选中
PF II时,先检查RR是否存在,不存在则把缓存的克隆版本加回去 - 选中其他选项时,隐藏餐厅框的同时确保RR选项已恢复,避免下次切换到PF II时出现异常
- 选中
- 性能优化:用变量缓存jQuery对象,避免重复查找DOM元素,提升页面响应速度
原HTML代码无需修改
<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <div class="form-row"> <!-- LOCATION --> <div class="form-group col-md-12 col-sm-12 col-12"> <label for="location" i18n-key="pages.leftovers.location"></label> <select required name="location" id="location" class="form-control"> <option value="PF I">PF I</option> <option value="PF II">PF II</option> <option value="PF II-extensão">PF II - EXTENSÃO</option> <option value="PF III"> PF III</option> <option value="RF">RF</option> </select> </div> </div> <div id="restaurantSelect"> <div class="form-row"> <!-- RESTAURANT --> <div class="form-group col-md-12 col-sm-12 col-12"> <label for="restaurant" i18n-key="pages.counters_temp.restaurant"></label> <select required name="restaurant" id="restaurant" class="form-control"> <option value="A">A</option> <option value="B">B</option> <option value="RR">RR</option> <option value="Lavanderia">Lavandeira</option> </select> </div> </div> </div>
内容的提问来源于stack exchange,提问作者Daniela Gross
相关产品推荐
相关产品推荐

