使用jQuery设置选中

问题描述 投票:1回答:2

我正在尝试更改此列表中的所选选项..它仅适用于某些而非其他人?

selectedVal将是Kelly Green,Navy等......

 var selectedVal = $(this).text();

 $("#product-variants-option-0 option[text=" + selectedVal+"]").attr("selected","selected") ;

这是选择列表:

<select class="single-option-selector" id="product-variants-option-0">
<option value="Gunmetal Heather">Gunmetal Heather</option>
<option value="Kelly Green">Kelly Green</option>
<option value="Navy">Navy</option>
</select>
jquery select selector options attr
2个回答
5
投票

在选择器中使用值属性而不是文本。即:

$("#product-variants-option-0 option[value=" + selectedVal+"]").attr("selected","selected") ;

3
投票

有一种更简单的方法来设置<select>元素的选定选项。

只需将jQuery's .val() method<select>本身联系起来:

$("#product-variants-option-0").val( selectedVal );
© www.soinside.com 2019 - 2024. All rights reserved.