← 中文资源

简体中文版本

selectedOptions 枚举多选的选中项

多选 select 用 selectedOptions 只拿选中的 option 元素,.value 在 multiple 下只回第一个;取消选中要走 option.selected 标志,空选时是空集合而非 null。

阅读英文原文

实现说明

select、picked 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 浏览器才是这里的运行环境:document 在 Node 里拿不到。
  • 直接运行文件,输出会带上标签,比如 picked:、value says:、after deselect:——输出的每一行都能指回产生它的那次调用。

常见问题

「selectedOptions 枚举多选的选中项」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

核心语句

const picked = [...select.selectedOptions].map((o) => o.value);

代码示例

const select = document.querySelector('#regions');
select.options[0].selected = true; // emea
select.options[2].selected = true; // apac

// selectedOptions is a live collection of picked <option> elements only.
const picked = [...select.selectedOptions].map((o) => o.value);
console.log('picked:', picked);

// value returns only the first selection — useless for multiple selects.
console.log('value says:', select.value);

// Deselecting through the collection is possible but the DOM is the
// source of truth: clear via the option's selected flag.
select.selectedOptions[0].selected = false;
console.log('after deselect:', [...select.selectedOptions].map((o) => o.value));

// Empty selection is an empty list, not null — safe to join directly.
select.options[0].selected = false;
select.options[2].selected = false;
console.log('payload:', select.selectedOptions.length === 0 ? [] : picked);