如何通过 JavaScript 在 <select> 中获取当前选择的 <option>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3301688/
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-23 04:05:28  来源:igfitidea点击:

How do you get the currently selected <option> in a <select> via JavaScript?

javascripthtmlhtml-select

提问by Paul D. Waite

How do you get the currentlyselected <option>of a <select>element via JavaScript?

如何通过 JavaScript获取当前选中<option><select>元素?

回答by Pat

This will do it for you:

这将为您做到:

var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )

回答by Amber

The .selectedIndexof the selectobject has an index; you can use that to index into the .optionsarray.

.selectedIndex所述的select对象具有的索引; 您可以使用它来索引.options数组。

回答by Ir Calif

var payeeCountry = document.getElementById( "payeeCountry" );
alert( payeeCountry.options[ yourSelect.selectedIndex ].value );

回答by Finesse

Using the selectedOptionsproperty:

使用selectedOptions属性:

var yourSelect = document.getElementById("your-select-id");
alert(yourSelect.selectedOptions[0].value);

It worksin all browsers except Internet Explorer.

适用于除 Internet Explorer 之外的所有浏览器。