How to find select option position?

家住魔仙堡 提交于 2019-12-21 04:23:07

问题


I'm trying to find an option's index.

For example, I would like to get 1 when I run the following fake code

JS:

$("#test[value='USD']").index() ?

HTML:

<select id='test'>
  <option value='CNY'>CNY</option>
  <option value='USD'>USD</option>
</select>

is this possible?


回答1:


You were very close, you want to use index on the option element, not the select:

var i = $("#test option[value='USD']").index();

Gratuitous live example

Note that this will break if your select contains optgroup elements. If so, you'll want to pass 'option' into index:

var i = $("#test option[value='USD']").index('option');

Live example (I changed the position so it's the 4th element for that example)




回答2:


from Reference

.index() can take a DOM node and returns an index, 
 We get back the zero-based position of the list item:



回答3:


Im sure there is a straight forward way of counting the index in such occasions i just can't remember it right now, but you could try creating a function that loops between each values, and raises a counter +1 each time, until you get $("#test").val("USD")



来源:https://stackoverflow.com/questions/6773123/how-to-find-select-option-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!