jQuery 设置选择索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1280499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:05:36  来源:igfitidea点击:

jQuery Set Select Index

jqueryjquery-selectors

提问by Marc

I have an select box:

我有一个选择框:

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

I'd like to set one of the options as "selected" based on it's selected index.

我想根据所选索引将其中一个选项设置为“已选择”。

For example, if I am trying to set "Number 3", I'm trying this:

例如,如果我尝试设置“Number 3”,我正在尝试:

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

But this doesn't work. How can I set an option as selected based on it's index using jQuery?

但这不起作用。如何根据使用 jQuery 的索引将选项设置为选定的选项?

Thanks!

谢谢!

回答by Marc

NOTE: answer is dependent upon jQuery 1.6.1+

注意:答案取决于 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


Thanks for the comment, .getwon't work since it returns a DOM element, not a jQuery one. Keep in mind the .eqfunction can be used outside of the selector as well if you prefer.

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

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


You can also be more terse/readable if you want to use the value, instead of relying on selecting a specific index:

如果您想使用value,而不是依赖于选择特定索引,您还可以更简洁/可读:

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

Note:.val(3)works as well for this example, but non-numeric values must be strings, so I chose a string for consistency.
(e.g. <option value="hello">Number3</option>requires you to use .val("hello"))

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

回答by dnoxs

This may also be useful, so I thought I'd add it here.

这也可能有用,所以我想我会在这里添加它。

If you would like to select a value based on the item's value and not the index of that item then you can do the following:

如果您想根据项目的值而不是该项目的索引选择一个值,那么您可以执行以下操作:

Your select list:

您的选择列表:

<select id="selectBox">
    <option value="A">Number 0</option>
    <option value="B">Number 1</option>
    <option value="C">Number 2</option>
    <option value="D">Number 3</option>
    <option value="E">Number 4</option>
    <option value="F">Number 5</option>
    <option value="G">Number 6</option>
    <option value="H">Number 7</option>
</select>

The jquery:

jQuery:

$('#selectBox option[value=C]').attr('selected', 'selected');
$('#selectBox option[value=C]').attr('selected', 'selected');

$('#selectBox option[value=C]').prop('selected', true);

The selected item would be "Number 2" now.

所选项目现在将是“编号 2”。

回答by Chris Brandsma

Try this instead:

试试这个:

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

回答by sean

Even simpler:

更简单:

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

回答by M Rostami

# Set element with index
$("#select option:eq(2)").attr("selected", "selected");

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

when you want to select with top ways for set selection , you can use
$('#select option').removeAttr('selected');for remove previous selects .

当您想使用顶级方式选择集合选择时,您可以使用
$('#select option').removeAttr('selected');删除以前的选择。

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

回答by hellojebus

I've always had issues with prop('selected'), the following has always worked for me:

我一直对 prop('selected') 有问题,以下一直对我有用:

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

回答by Anonymous

What's important to understand is that val()for a selectelement returns the value of the selected option, but not the number of element as does selectedIndexin javascript.

什么是重要的一点是,val()对于一个select元素返回所选择的选项的值,而不是元素的数量一样selectedIndex在JavaScript。

To select the option with value="7"you can simply use:

要选择该选项,value="7"您只需使用:

$('#selectBox').val(7); //this will select the option with value 7.

To deselect the option use an empty array:

要取消选择该选项,请使用空数组:

$('#selectBox').val([]); //this is the best way to deselect the options

And of course you can select multiple options*:

当然,您可以选择多个选项*:

$('#selectBox').val([1,4,7]); //will select options with values 1,4 and 7

*However to select multiple options, your <select>element must have a MULTIPLEattribute, otherwise it won't work.

*但是要选择多个选项,您的<select>元素必须有一个MULTIPLE属性,否则将不起作用。

回答by NicolasBernier

Try this:

尝试这个:

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

Eventually, trigger a .change event :

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

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

回答by Andrew

Hope this could help Too

希望这也能有所帮助

$('#selectBox option[value="3"]').attr('selected', true);

回答by dabar

select 3rd option

选择第三个选项

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

Example on jsfiddle

jsfiddle 示例