使用jQuery选择的设置
题
我正在尝试更改此列表中的选项。它仅适用于某些而不是其他功能?
SelectedVal要么是凯利·格林(Kelly Green),海军等...
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>
解决方案
使用值属性而不是选择器中的文本。 IE:
$("#product-variants-option-0 option[value=" + selectedVal+"]").attr("selected","selected") ;
其他提示
有一种更简单的方法来设置选定的选项 <select>
元素。
只是打电话 jQuery的 .val()
方法 反对这 <select>
本身:
$("#product-variants-option-0").val( selectedVal );
不隶属于 StackOverflow