如何获得所选的选项ID?

h3n*_*h3n 12 html javascript

从HTML中选择要获取的值:

options[selectedIndex].value

如果我想获得"id"所选的选项怎么办?

Mic*_*man 12

没有做太多假设(即select是一个有效的SELECT元素),

var options = select.options;
var id      = options[options.selectedIndex].id;
var value   = options[options.selectedIndex].value;
Run Code Online (Sandbox Code Playgroud)

要么,

var options = select.options;
var value   = (options.selectedIndex != -1) ? options[selectedIndex].value : null;
var id      = (options.selectedIndex != -1) ? options[selectedIndex].id : null;
Run Code Online (Sandbox Code Playgroud)

始终检查虚假(或评估为false的值).Ex 2将变量设置为null(如果没有选择任何内容).


zom*_*bat 8

它很简单:

options[selectedIndex].id
Run Code Online (Sandbox Code Playgroud)