jQuery - 按元素id设置select index

Mar*_*ski 9 jquery select jquery-selectors

<select id="mySelect">
  <option id="sel01" value="some value">some value</option>
  <option id="sel02" value="some other value">some other value</option>
  <option id="sel03" value="maybe me">maybe me</option>
  <option id="sel04" value="and another one">and another one</option>
</select>
Run Code Online (Sandbox Code Playgroud)

我想选择一个使用jQuery的选项,但不是按值:

$("#mySelect").val(1);
Run Code Online (Sandbox Code Playgroud)

但是由元素id.

谢谢你的回答.

und*_*ned 12

你可以使用prop方法.

var id = 'sel02';

$('#mySelect option').filter(function(){
   return this.id === id
}).prop('selected', true);
Run Code Online (Sandbox Code Playgroud)

要么:

$('#' + id).prop('selected', true);
Run Code Online (Sandbox Code Playgroud)

或者,如果要根据索引选择选项,可以使用eq方法:

$('#mySelect option').eq(1).prop('selected', true);
Run Code Online (Sandbox Code Playgroud)