2014-10-31 41 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();