如何基于选项文本查找Select元素的选项索引且不选中选项
检查select选项是否存在且不修改选中状态
你的问题出在这行代码:
let x = select.value = [...select.options].findIndex(option => option.text === 'I' + value_option);
这里把findIndex的返回值直接赋值给了select.value,哪怕结果是-1(表示找不到选项),也会强制修改select的选中状态。
要实现只检查选项是否存在、不修改选中状态的需求,只需要单独计算索引,不赋值给select.value即可:
修正后的代码(获取索引并判断)
<select id="select"> <option value="13">I1</option> <option value="23">I21</option> <option value="954">I33</option> </select> <script> var select = document.getElementById('select'); findInvoice(44); function findInvoice(value_option) { const targetText = 'I' + value_option; // 仅计算索引,不修改select的选中状态 const optionIndex = [...select.options].findIndex(option => option.text === targetText); console.log(optionIndex); // 找不到时返回-1,找到时返回对应索引 // 可选:直接判断是否存在 if (optionIndex !== -1) { console.log('目标选项存在'); } else { console.log('目标选项不存在'); } } </script>
更简洁的判断方式(不需要索引时用some)
如果只需要判断是否存在,不需要获取索引,可以用some方法直接返回布尔值:
function findInvoice(value_option) { const targetText = 'I' + value_option; const optionExists = [...select.options].some(option => option.text === targetText); console.log(optionExists); // 存在返回true,不存在返回false }
内容的提问来源于stack exchange,提问作者user1286956
相关产品推荐
相关产品推荐

