Javascript 如何根据值获取期权的索引
所以我现在有一个Javascript 如何根据值获取期权的索引,javascript,html,Javascript,Html,所以我现在有一个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
字段,看起来像这样:
<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的情况下有效地获取valuebar
的索引
有没有一种方法可以做到这一点,而不必遍历每个选项,对照我的选项检查值,然后将其设置为选中,如果它与我的值相同
非常感谢您提供的任何见解您可以与索引
结合使用:
var selected = document.querySelector( '#foo > option[value="bar"]' );
console.log(selected.index);
oops!解开我的领带这是绝对的金子!我到处找这样的东西!非常感谢。我会接受的,所以让我笑。