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

如何获取多选select中被点击选项的ID?

如何获取多选select中被点击的option的ID?

我有如下的select元素:

<select id="multi_select" multiple>
    <option id="1" value="one">One</option>
    <option id="2" value="two">Two</option>
    <option id="3" value="three">Three</option>
    <option id="4" value="four">Four</option>
    <option id="5" value="five">Five</option>
</select>

我想获取被点击的option元素的ID,尝试了以下代码:

$("#multi_select").on('change', function () {
    let id = this.options[this.selectedIndex].id;
});

但无法正常工作——它只会返回最上方选中项的ID。比如点击One后按住Shift点击Two(多选),返回的ID是1(最上方选中项的ID),但我需要的是被点击的那个选项的ID。


编辑:添加可运行代码片段:

$("#multi_select").on('change', function() {
  let id = this.options[this.selectedIndex].id;
  console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="multi_select" multiple>
        <option id="1" value="one">One</option>
        <option id="2" value="two">Two</option>
        <option id="3" value="three">Three</option>
        <option id="4" value="four">Four</option>
        <option id="5" value="five">Five</option>
</select>

解决方案

change事件本身无法直接获取被点击的选项,因为它仅在选中状态变化时触发,不会传递具体点击的元素。针对这个问题,有两种可行的处理方式:

方法1:直接给option绑定click事件

这是最直接的方式,鼠标点击任意option时都会触发事件,能直接拿到被点击的元素:

$("#multi_select option").on('click', function() {
    console.log("被点击的option ID:", this.id);
});

这种方式在Shift/Ctrl批量选择时,每一个被点击触发选中的选项都会单独触发一次click事件,能准确捕捉每次点击的目标。

方法2:兼容键盘操作的进阶方案

如果需要兼容键盘操作(比如方向键+空格选中选项),可以记录之前的选中状态,在change事件中对比找出变化的选项:

// 记录上一次选中的选项ID集合
let prevSelectedIds = new Set();

$("#multi_select").on('change', function() {
    // 获取当前所有选中的选项ID
    let currentSelected = Array.from(this.selectedOptions).map(opt => opt.id);
    let currentSelectedSet = new Set(currentSelected);
    
    // 找出新增选中的选项
    let added = [...currentSelectedSet].filter(id => !prevSelectedIds.has(id));
    // 找出取消选中的选项
    let removed = [...prevSelectedIds].filter(id => !currentSelectedSet.has(id));
    
    if(added.length > 0) {
        console.log("新增选中的option ID:", added);
    }
    if(removed.length > 0) {
        console.log("取消选中的option ID:", removed);
    }
    
    // 更新记录的选中状态
    prevSelectedIds = currentSelectedSet;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:31:23