ion-select多选场景下如何根据选中项取消其他所有选项的选中状态
实现方案
修改模板代码
给ion-select添加唯一ID方便JS获取元素,修改后代码如下:
<ion-item color="dark"> <ion-select multiple id="numberSelect" value="any"> <ion-select-option value="any">Any</ion-select-option> <ion-select-option value="01">1</ion-select-option> <ion-select-option value="02">2</ion-select-option> <ion-select-option value="03">3</ion-select-option> <ion-select-option value="04">4</ion-select-option> <ion-select-option value="05">5</ion-select-option> <ion-select-option value="06">6</ion-select-option> <ion-select-option value="07">7</ion-select-option> <ion-select-option value="08">8</ion-select-option> </ion-select> </ion-item>
编写JS交互逻辑
直接监听ion-select的ionChange值变化事件,按照需求做选中值修正即可:
document.addEventListener('DOMContentLoaded', () => { const numberSelect = document.getElementById('numberSelect'); // 存储上一次选中值,用于判断操作类型 let lastSelected = numberSelect.value || ['any']; numberSelect.addEventListener('ionChange', (event) => { const currentVal = event.detail.value; const hasAny = currentVal.includes('any'); const hasOther = currentVal.some(item => item !== 'any'); // 场景1:之前已选中Any,现在又选了其他选项,移除Any if (hasAny && hasOther && lastSelected.includes('any')) { numberSelect.value = currentVal.filter(item => item !== 'any'); } // 场景2:之前选了其他选项,现在新增选中Any,只保留Any else if (hasAny && hasOther && !lastSelected.includes('any')) { numberSelect.value = ['any']; } // 更新上次选中值记录 lastSelected = [...numberSelect.value]; }); });
逻辑验证
- 选中Any后再选任意数值选项:Any会自动取消选中,仅保留新选的数值选项
- 选中多个数值选项后再选Any:所有数值选项会自动取消选中,仅保留Any
如果你使用的是Angular/Vue/React等框架,只需要绑定对应框架的ionChange事件,核心逻辑和上述代码完全一致,不需要调整判断规则。
内容的提问来源于stack exchange,提问作者pilotman
相关产品推荐
相关产品推荐

