Select2多选组件:点击已选选项框如何获取其对应option值或对象
解决方案
你拿到的select2-id本质是Select2内部生成的元素唯一标识,可以直接和select2('data')返回的选中项数组匹配,也可以用更稳定的自定义属性方案避免依赖内部私有属性:
方案1:直接匹配现有属性
select2('data')返回的每个选中项对象都包含_resultId私有属性,和你获取到的data('select2-id')值完全对应,直接遍历匹配即可:
$('#mySelect2').next('span').find('ul').on('click', '.select2-selection__choice', function (e) { const clickId = $(this).data('select2-id'); const selectedList = $('#mySelect2').select2('data'); // 匹配对应选项对象 const currentOption = selectedList.find(item => item._resultId === clickId); console.log('完整选项对象', currentOption); console.log('选项值', currentOption.id); console.log('选项文本', currentOption.text); });
注意:_resultId属于Select2内部私有属性,版本升级时存在属性名变更的可能性,对兼容性要求高可以用方案2
方案2:自定义模板绑定数据(更稳定)
初始化Select2时自定义选中项渲染模板,提前把完整选项数据绑定到元素上,不需要依赖Select2内部属性:
// Select2初始化配置 $('#mySelect2').select2({ // 你的其他原有配置 templateSelection: function (option, container) { // 将完整选项对象绑定到元素的data属性上 $(container).data('option-info', option); return option.text; } }); // 点击事件逻辑 $('#mySelect2').next('span').find('ul').on('click', '.select2-selection__choice', function (e) { const currentOption = $(this).data('option-info'); console.log('完整选项对象', currentOption); });
内容的提问来源于stack exchange,提问作者Duddy67
相关产品推荐
相关产品推荐

