如何根据选项文本获取选项索引

how to get option index based on option text

本文关键字:选项 获取 索引 文本 何根      更新时间:2023-09-26

我试图根据选项文本找到选项索引。我的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而不是7

所以请帮我解决这个问题。

您将使用:contains伪选择器:

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

索引应该从0开始,因此文本"Rich Yellow"的索引位置为6。

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

Fiddle

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

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