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

React中如何获取选中选项所属optgroup的信息?

解决方法

首先得修正你的select结构——目前reserveOptions和firstTeamOptions是放在对应optgroup标签外面的,这会导致这些选项不属于任何分组,根本拿不到分组信息。先把动态选项移到对应的optgroup内部:

<div className="">
  <select
    onChange={(e) => {
      // 获取选中的option元素
      const selectedOption = e.target.options[e.target.selectedIndex];
      // 获取所属的optgroup
      const optgroup = selectedOption.parentElement;
      // 初始化分组名称
      let groupName = null;
      
      // 判断当前选项是否在optgroup内
      if (optgroup.tagName === 'OPTGROUP') {
        groupName = optgroup.label;
      }

      // 输出结果
      console.log('选中值:', e.target.value);
      console.log('所属分组:', groupName);
    }}
    className=" bg-gray-500"
  >
    <option>Pick Player</option>
    <optgroup label="Substitutes">{subOptions}</optgroup>
    <optgroup label="Reserves">{reserveOptions}</optgroup>
    <optgroup label="First Team">{firstTeamOptions}</optgroup>
    <optgroup label=""></optgroup>
    <option>+ Add Player</option>
  </select>
</div>

关键步骤说明:

  • 通过e.target.selectedIndex拿到选中项在options列表里的索引
  • 用e.target.options[index]获取到具体的option DOM元素
  • 调用option.parentElement得到它的父元素,也就是对应的optgroup
  • 判断父元素是否是optgroup(避免像"Pick Player"这种顶级选项报错),如果是就取它的label属性

这样就能同时获取选中值和所属的分组名称了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 03:25:15