如何修改Select2已选选项的Tooltip显示内容为对应value值?
问题描述
我用Select2实现了一个多选下拉框,当前鼠标悬停已选选项时,Tooltip显示的是选项内的文本内容,但我希望Tooltip显示该选项对应的value值(如xyz、abc)。我尝试通过遍历相关元素:
$($('span.select2.select2-container').find('.select2-selection__rendered')).children().map(function () { })
但该方法无效,请问应该如何实现?
解决方案
要实现这个需求,需要针对Select2生成的已选标签元素动态设置title属性为对应选项的value值,同时覆盖初始加载和用户选择新选项两种场景:
1. 初始加载时设置Tooltip
页面初始化完成后,遍历原生<select>中已选中的<option>,匹配Select2生成的标签元素并设置title:
$(document).ready(function() { $('.reminder-numbers-select').select2({ tags: true, dir: "rtl", dropdownAutoWidth: true, width: '100%', }); // 给初始已选标签设置Tooltip $('.select2-selection__choice').each(function() { // 获取标签显示的文本内容 const choiceText = $(this).find('.select2-selection__choice__remove').next().text().trim(); // 匹配原生select中对应文本的option,获取其value const optionValue = $('.reminder-numbers-select option:contains("' + choiceText + '")').val(); // 设置title属性 $(this).attr('title', optionValue); }); });
2. 监听选择事件,实时更新新选项的Tooltip
当用户选择新选项时,通过Select2的select:select事件捕获选中数据,给刚生成的标签设置title:
// 监听Select2选择事件,实时设置新选项的Tooltip $('.reminder-numbers-select').on('select:select', function(e) { const selectedData = e.params.data; // 定位刚生成的已选标签 const newChoiceTag = $('.select2-selection__choice').last(); // 将选中项的value设置为Tooltip内容 newChoiceTag.attr('title', selectedData.id); });
完整代码示例
合并上述逻辑后的完整JS代码:
$(document).ready(function() { $('.reminder-numbers-select').select2({ tags: true, dir: "rtl", dropdownAutoWidth: true, width: '100%', }); // 初始化已选标签的Tooltip $('.select2-selection__choice').each(function() { const choiceText = $(this).find('.select2-selection__choice__remove').next().text().trim(); const optionValue = $('.reminder-numbers-select option:contains("' + choiceText + '")').val(); $(this).attr('title', optionValue); }); // 监听选择事件,动态设置新选项的Tooltip $('.reminder-numbers-select').on('select:select', function(e) { const selectedData = e.params.data; const newChoiceTag = $('.select2-selection__choice').last(); newChoiceTag.attr('title', selectedData.id); }); });
关键说明
- Select2生成的已选标签类名为*
.select2-selection__choice*,通过该类定位目标元素; - 初始选项通过标签文本匹配原生
<option>获取value; - 新选择的选项可直接通过Select2事件返回的
selectedData.id获取对应value(与原生<option>的value属性一致)。
内容的提问来源于stack exchange,提问作者Meet Gondaliya
相关产品推荐
相关产品推荐

