我有一个选择框:

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

其他回答

根据选择列表中的值选择项目(特别是如果选项值中有空格或奇怪的字符),只需这样做:

$("#SelectList option").each(function () {
    if ($(this).val() == "1:00 PM")
        $(this).attr('selected', 'selected');
});

此外,如果你有一个下拉菜单(而不是多选菜单),你可能需要暂停;这样就不会覆盖第一个找到的值。

我需要一个解决方案,没有硬编码值在js文件;使用selectedIndex。大多数给出的解决方案在一个浏览器上失败。这似乎在FF10和IE8中工作(其他人能在其他版本中测试吗)

$("#selectBox").get(0).selectedIndex = 1; 

:不久

$ (" # selectBox”)。attr(“selectedIndex index)

其中index是所选的整数索引。

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

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

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

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