我有一个选择框:

<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?

谢谢!


当前回答

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

其他回答

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

我也遇到过同样的问题。 首先你需要遍历事件(即哪个事件先发生)。

例如:

第一个事件是生成带有选项的选择框。

第二个事件是使用val()等函数选择默认选项。

您应该确保第二个事件应该发生在第一个事件之后。

为了实现这个目标,需要用到两个函数,比如generateSelectbox()(用于生成选择框)和selectDefaultOption()

您需要确保只有在generateSelectbox()执行之后才调用selectDefaultOption()

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

$("#selectBox").get(0).selectedIndex = 1; 
# Set element with index
$("#select option:eq(2)").attr("selected", "selected");

# Set element by text
$("#select").val("option Text").attr("selected", "selected");

当你想用顶部方式选择集合选择时,你可以使用 $(" #选择选项”).removeAttr(“选择”);用于删除先前的选择。

# Set element by value
$("#select").val("2");

# Get selected text
$("#select").children("option:selected").text();  # use attr() for get attributes
$("#select option:selected").text(); # use attr() for get attributes 

# Get selected value
$("#select option:selected").val();
$("#select").children("option:selected").val();
$("#select option:selected").prevAll().size();
$("option:selected",this).val();

# Get selected index
$("#select option:selected").index();
$("#select option").index($("#select option:selected"));

# Select First Option
$("#select option:first");

# Select Last Item
$("#select option:last").remove();


# Replace item with new one
$("#select option:eq(1)").replaceWith("<option value='2'>new option</option>");

# Remove an item
$("#select option:eq(0)").remove();

选择第三个选项

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

关于jsfiddle的示例