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

如何在Bootstrap 5多选下拉框中获取触发change事件的选中选项值

如何识别多选下拉框中触发change事件的选项值

对于多选的<select>标签,默认的$(this).val()或e.currentTarget.value确实会返回所有选中值的数组。要拿到触发change事件的单个选项,可以用以下两种方法:

方法1:对比前后选中状态,找出变化项

先在外部保存上次选中的所有值,每次change事件触发时,和当前选中值对比,就能定位到刚被选中或取消的选项:

// 保存上次选中的值
let lastSelected = $('#ddlCostCenters').val() || [];

$('#ddlCostCenters').on('change', function (e) {
  const currentSelected = $(this).val() || [];
  // 找出新增的选项(刚被选中的)
  const added = currentSelected.filter(item => !lastSelected.includes(item));
  // 找出移除的选项(刚被取消的)
  const removed = lastSelected.filter(item => !currentSelected.includes(item));
  
  if (added.length > 0) {
    alert('刚选中的选项值:' + added[0]);
  } else if (removed.length > 0) {
    alert('刚取消的选项值:' + removed[0]);
  }
  
  // 更新上次选中值
  lastSelected = currentSelected;
});

方法2:给每个<option>绑定click事件

直接监听下拉框里每个选项的点击事件,这样就能直接拿到被点击的选项值:

$('#ddlCostCenters option').on('click', function() {
  const optionValue = $(this).val();
  const isSelected = $(this).is(':selected');
  
  if (isSelected) {
    alert('选中的选项值:' + optionValue);
  } else {
    alert('取消的选项值:' + optionValue);
  }
});

注意:方法2在部分浏览器(比如Firefox)中,通过键盘操作选中/取消选项时可能不会触发click事件,所以如果需要兼容键盘操作,优先用方法1。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 10:45:33