如何根据值获取期权的索引

How to get the Index of an option based on a value

本文关键字:索引 获取 何根      更新时间:2023-09-26

所以我目前有一个看起来像这样的select字段:

<select id = "foo">
   <option value = "example">This example</option>
   <option value = "example2">This example Again</option>
   <option value = "bar">This is just a bar</option>
</select>

如果提交的表单返回错误,它会向我发送回对象中的所有值,我需要重新填充表单。

我的问题:如何在不使用jQuery的情况下有效地获取值bar的索引?

有没有办法做到这一点,而不必遍历每个选项,根据我拥有的值检查值,然后将其设置为选中,如果它与我的值相同?

任何见解都非常感谢

您可以将

querySelector()index结合起来:

var selected = document.querySelector( '#foo > option[value="bar"]' );
console.log(selected.index);

jsFiddle 演示