我有一个选择框:

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

谢谢!


当前回答

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

其他回答

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

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

NB:

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

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

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

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

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

试试这个:

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

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

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

如果你的选择框是一个multipl,你也可以初始化多个值:

$('#selectBox').val(['A', 'B', 'C']);