我有一个选择框:

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

谢谢!


当前回答

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

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

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

其他回答

# 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 option')[3].selected = true;

注意:答案依赖于jQuery 1.6.1+

$('#selectBox :nth-child(4)').prop('selected', true); // To select via index
$('#selectBox option:eq(3)').prop('selected', true);  // To select via value

感谢您的评论,.get将无法工作,因为它返回一个DOM元素,而不是jQuery元素。请记住,如果您愿意,.eq函数也可以在选择器之外使用。

$('#selectBox option').eq(3).prop('selected', true);

如果你想使用值,而不是依赖于选择特定的索引,你也可以更简洁/可读:

$("#selectBox").val("3");

注意:.val(3)对于这个例子也很有效,但是非数字值必须是字符串,所以为了保持一致性,我选择了字符串。 (例如:<option value="hello">Number3</option>要求你使用.val("hello"))

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

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

我经常使用触发器(“改变”)来让它工作

$('#selectBox option:eq(position_index)').prop('selected', true).trigger('change');

示例:id select = selectA1, position_index = 0 (select中的第一个选项):

$('#selectA1 option:eq(0)').prop('selected', true).trigger('change');