如何找到选择位置? [英] How to find select option position?

查看:119
本文介绍了如何找到选择位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找选项的索引。

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

例如,当我运行以下假代码时,我想获得1

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>

这可能吗?

推荐答案

你非常接近,你想使用 index 选项元素,而不是选择

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

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

免费直播示例

请注意,如果您的选择包含 optgroup 元素。如果是这样,您需要将'选项'传递到 index

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');

实例(我改变了位置,因此它是该示例的第4个元素)

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

这篇关于如何找到选择位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆