按值获取下拉列表/组合框的索引(客户端)

Get index of dropdown/combobox by value (client side)?

本文关键字:索引 客户端 组合 获取 下拉列表      更新时间:2023-09-26

我认为这会很简单,但有没有一种方法可以在下拉列表/组合框中获得值的索引,而无需循环项目?

我猜您谈论的是select标记,您正试图通过其值来获取选项的索引。如果是这样,以下是您需要做的:

// Get the select
var select = document.getElementById('mySelect');
// Get the option
var option = select.querySelector('option[value="myValue"]');
// Get the index of that option
var index = Array.prototype.indexOf.call( select.children, option );

您不需要jQuery。您可以使用现代Javascript以本机方式完成此操作。

var myOption = document.querySelector('option[value="audi"]');
console.log(myOption.index); //returns index = 3

此处的示例:http://jsfiddle.net/08qzLgbh/

基于此HTML:

<select>
  <option value="volvo">Volvo</option> <!-- index 0 -->
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option> <!-- index 3 -->
</select> 

答案涉及jQuery和选择器,而且可能并不那么高效,但这可能是您想要的:

var o = $('option[value="something"]','#mycombo');

足够简单(: