jquery选择选项

时间:2012-11-11 15:19:55

标签: javascript jquery

我有以下选项框:

<label for="inputselection1">Input #1:</label>
<select id="inputselection1" name="unittype">
<option value="1">Miner</option>
<option value="2">Puffer</option>
<option value="3">Snipey</option>
<option value="4">Max</option>
<option value="5">Firebot</option>
</select><br>

但是,当我执行以下jquery选项onload时,文本(选定选项)不会更改为Max:

$("#inputselection1 option[text=Max]").attr("selected","selected");

是什么给出了?

谢谢!

3 个答案:

答案 0 :(得分:1)

使用.val()按选项值设置选择值:

$("#inputselection1").val(4);​

如果您坚持按文字选择,请使用:

$("#inputselection1 option").filter(function() {
    return $(this).text() === 'Max';
}).attr("selected", "selected");

答案 1 :(得分:1)

如果您想通过选项文本进行选择,可以使用filter功能

$("#inputselection1 option").filter(function() {
    return $(this).text() === 'Max';
}).prop("selected", true);

Fiddle

答案 2 :(得分:0)

$(“#inputselection1 option [value = 4]”)。attr(“selected”,“selected”);

取自

jQuery Set Select Index