如何使用jQuery获取multiple下拉框最后一次选中的选项值
解决方案
你可以通过记录上一次选中状态,和当前选中状态做差集的方式拿到最新操作的选项,完整实现代码如下:
// 存储上一次选中的选项值 let lastSelectedServices = []; $(document).on("change", '.js-services', function() { // 获取当前所有选中的值,无选中时设为空数组避免报错 const currentSelected = $(this).val() || []; // 计算本次新增选中的项(当前存在、上次不存在的就是刚选中的) const newlySelected = currentSelected.filter(val => !lastSelectedServices.includes(val)); // 计算本次取消选中的项(上次存在、当前不存在的就是刚取消的) const newlyDeselected = lastSelectedServices.filter(val => !currentSelected.includes(val)); // 处理刚选中的选项 if (newlySelected.length) { // 遍历所有本次新增的选中项(支持按ctrl/shift批量选中的场景) newlySelected.forEach(val => { // 更稳妥的方式查找对应option,避免value带特殊字符时属性选择器失效 const selectedOption = $(this).find('option').filter(function() { return $(this).val() === val; }); // 读取自定义属性 const serviceText = selectedOption.data('text'); const serviceDuration = selectedOption.data('duration'); const serviceCost = selectedOption.data('cost'); // 这里可以写你自己的业务逻辑 console.log('最新选中的项值:', val); console.log('对应text属性:', serviceText); }) // 如果只需要最后一个选中的单个值,直接取 newlySelected[newlySelected.length - 1] 即可 } // 更新上一次选中状态,供下次事件触发时对比 lastSelectedServices = [...currentSelected]; });
原理说明
多选select的change事件本身不会直接返回本次操作的单个选项,所以我们通过对比两次选中数组的差异,就能精准定位到本次新增选中或者取消选中的选项,兼容批量选中、取消选中的所有场景。
内容的提问来源于stack exchange,提问作者Fokrule
相关产品推荐
相关产品推荐

