You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取HTML多选select元素当前选中项的数组?

如何获取HTML多选select元素当前选中项的数组,例如["Apple", "Orange"]?

你提到的selectedOptions其实就是标准方案的核心,只需要把它转成数组并提取所需内容即可,无需复杂解析。

实现代码

HTML

<select multiple id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>

JavaScript

const selectEl = document.getElementById('mySelect');

// 监听选中状态变化(用change事件比click更精准)
selectEl.addEventListener('change', () => {
  // 将选中的option集合转为数组,提取文本组成目标数组
  const selectedItems = Array.from(selectEl.selectedOptions).map(opt => opt.text);
  console.log(selectedItems);
});

关键说明

  • selectedOptions是HTML5标准提供的属性,直接返回所有选中的<option>元素,属于类数组的HTMLCollection类型。
  • 用Array.from()把类数组转为真正的数组,再通过map方法提取每个option的text(如果需要value,换成opt.value即可)。
  • 改用change事件监听更合理,因为多选select的选中状态可以通过键盘等非点击方式改变。

内容的提问来源于stack exchange,提问作者Basj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:20:26