Javascript 如何获取选定的选项 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1904827/
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
How to get selected option ID?
提问by h3n
to get the selected value from HTML select:
从 HTML select 中获取选定的值:
options[selectedIndex].value
options[selectedIndex].value
what if i want to get the "id"on the selected option?
如果我想获得"id"所选选项怎么办?
采纳答案by zombat
It's as simple as:
这很简单:
options[selectedIndex].id
回答by Michiel Kalkman
Without making too many assumptions (i.e. selectis a valid SELECT Element),
不做太多假设(即select是一个有效的 SELECT 元素),
var options = select.options;
var id = options[options.selectedIndex].id;
var value = options[options.selectedIndex].value;
or,
或者,
var options = select.options;
var value = (options.selectedIndex != -1) ? options[selectedIndex].value : null;
var id = (options.selectedIndex != -1) ? options[selectedIndex].id : null;
Always check for falsity(or values that evaluate to false). Ex 2 sets variables to null(if there is nothing selected).
始终检查错误(或评估为false 的值)。Ex 2 将变量设置为null(如果没有选择任何内容)。

