我有一个选择框:

<select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
  <option value="3">Number 3</option>
  <option value="4">Number 4</option>
  <option value="5">Number 5</option>
  <option value="6">Number 6</option>
  <option value="7">Number 7</option>
</select>

我想将其中一个选项设置为“选定”基于它的选定索引。

例如,如果我试图设置“数字3”,我尝试这样做:

$('#selectBox')[3].attr('selected', 'selected');

但这行不通。我如何设置一个选项,因为选择基于它的索引使用jQuery?

谢谢!


当前回答

选择第三个选项

$('#selectBox').val($('#selectBox option').eq(2).val());

关于jsfiddle的示例

其他回答

纯javascript selectedIndex属性是正确的方法,因为它是纯javascript,可以跨浏览器工作:

$('#selectBox')[0].selectedIndex=4;

这是一个jsfiddle演示,有两个下拉列表,使用一个来设置另一个:

<select onchange="$('#selectBox')[0].selectedIndex=this.selectedIndex">
  <option>0</option>
  <option>1</option>
  <option>2</option>
</select>

<select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
</select>

你也可以在改变selectedIndex之前调用它,如果你想要的是option标签上的“selected”属性(这里是fiddle):

$('#selectBox option').removeAttr('selected')
   .eq(this.selectedIndex).attr('selected','selected');

更简单:

$('#selectBox option')[3].selected = true;

试试这个:

$('select#mySelect').prop('selectedIndex', optionIndex);

最后,触发一个.change事件:

$('select#mySelect').prop('selectedIndex', optionIndex).change();

重要的是,理解一个select元素的val()返回所选选项的值,而不是像javascript中的selectedIndex那样返回元素的数量。

要选择值为"7"的选项,你可以简单地使用:

$('#selectBox').val(7); //this will select the option with value 7.

要取消选择该选项,请使用空数组:

$('#selectBox').val([]); //this is the best way to deselect the options

当然,您可以选择多个选项*:

$('#selectBox').val([1,4,7]); //will select options with values 1,4 and 7

*但是要选择多个选项,<select>元素必须有multiple属性,否则它将不起作用。

NB:

$('#selectBox option')[3].attr('selected', 'selected') 

是不正确的,数组遵从得到你的dom对象,而不是一个jquery对象,所以它将失败的TypeError,例如在FF与:"$('#selectBox选项')[3].attr()不是一个函数。"