我有一个选择框:

<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(3);

其他回答

更简单:

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

如果你只是想根据一个项目的特定属性选择一个项目,那么jQuery的[prop=val]类型选项将获得该项目。现在我不关心索引,我只需要元素的值。

$('#mySelect options[value=3]).attr('selected', 'selected');

选择第三个选项

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

关于jsfiddle的示例

我一直有问题与道具(“选定”),以下一直为我工作:

//first remove the current value
$("#selectBox").children().removeAttr("selected");
$("#selectBox").children().eq(index).attr('selected', 'selected');

重要的是,理解一个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属性,否则它将不起作用。