2014-10-31 57 views
1

我试图找到选项索引基于选项文本。我的HTML代码如下。如何根据选项文本获取选项索引

<select multiple="multiple" onchange="dependentOptions.select(this); opConfig.reloadPrice();optionImages.showImage(this);" title="" class="multiselect product-custom-option" id="select_472" name="options[472][]" > 
<option selected="selected" value="3364">Black </option> 
<option selected="selected" value="3365">White </option> 
<option value="3366">Cool Grey #9 </option> 
<option value="3367">Red </option> 
<option value="3368">Fire Red </option> 
<option value="3369">Orange </option> 
<option value="3370">Rich Yellow </option> 
<option value="3371">Primrose Yellow </option> 
<option value="3372">Light Green </option> 
</select> 

,我的剧本是这样的

jQuery("#select_472 select option:[text=Rich Yellow]").index(); 

但它返回我-1 insted的7

所以,请大家帮我SOVE这一点。

+0

第二个'select'在jQuery选择中是错误的,你应该删除它。 – alalp 2014-10-31 11:43:16

+0

其他一些选项在这里:http://stackoverflow.com/questions/813477/jquery-selector-where-text-some-value – Will 2014-10-31 11:51:05

+0

请注意,索引是基于零的,所以在这里它将是6而不是7 – 2014-10-31 11:52:39

回答

2

你会使用:contains伪选择:

jQuery("#select_472 option:contains('Rich Yellow')").index(); 
+0

可能是一些与':contains'问题,例如在火红色和红色之间 – 2014-10-31 11:56:26

+0

@ A.Wolff是的,这是一个好点!过滤器是一个更好的选择。 – dfsq 2014-10-31 11:59:44

1

的指数应该在0这样的文字 '富饶的黄海' 将开始成为指数位置6.

$("#select_472 option[value='3370']").index(); 

$("#select_472 option:contains('Rich Yellow ')").index(); 

Fiddle

+1

'基于选项文本'。你正在脱离价值而不是文字。 – 2014-10-31 11:52:20

+0

涉及“价值= ......”的正是我一直在寻找的东西。所有其他的答案,其中一些非常聪明,我发现实现这个任务似乎使用强力循环选项。但是,从价值中获得指数的方式(显然)不会。因此,尽管没有回答OP的具体问题,我还是加上了你。 – 2017-08-10 18:12:57

1

你可以过滤它(并修剪文本值),看起来更安全:

jQuery("#select_472 option").filter(function(){ 
    return $.trim($(this).text()) === "Rich Yellow" 
}).index(); 
相关问题