如何在Select2标签功能中插入重复文本标签及选中不显示问题求助
Select2选中自定义生成标签不显示的问题修复
问题说明
在Select2多选模式下,输入文本后通过createTag生成两个前缀不同的标签选项,但选中其中一个选项时,选中项无法显示在输入框内。
原代码
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <div> <select id="test" class="form-control" multiple="multiple"></select> </div> <script> $("#test").select2({ tags: true, tokenSeparators: [',', ' '], createTag: function (params) { var term = $.trim(params.term); if (term === '') { return null; } return [ { id: "test1_"+term, text: "test1_"+term, newTag: "R" }, { id: "test2_"+term, text: "test2_"+term, newTag: "W" }, ] }, insertTag: function (data, tag) { data.push(tag[0]); data.push(tag[1]); } }); </script>
问题原因
insertTag函数的参数tag是用户选中的单个标签对象,而非createTag返回的数组。原代码中尝试访问tag[0]和tag[1]会得到undefined,导致无法将选中的标签添加到选择数据中,因此输入框内不会显示选中项。
修复方案
方案1:允许选中单个标签并正常显示
修改insertTag函数,直接将选中的单个标签对象添加到数据中:
$("#test").select2({ tags: true, tokenSeparators: [',', ' '], createTag: function (params) { var term = $.trim(params.term); if (term === '') { return null; } return [ { id: "test1_"+term, text: "test1_"+term, newTag: "R" }, { id: "test2_"+term, text: "test2_"+term, newTag: "W" }, ] }, insertTag: function (data, tag) { // 直接添加选中的单个标签 data.push(tag); } });
方案2:输入文本后自动添加两个标签(无需手动选择)
如果需求是输入文本后自动生成并添加两个标签,而非让用户选择其中一个,可以通过修改insertTag逻辑实现:
$("#test").select2({ tags: true, tokenSeparators: [',', ' '], createTag: function (params) { var term = $.trim(params.term); if (term === '') { return null; } // 返回临时标签用于触发插入逻辑 return { id: term, text: term, newTag: true } }, insertTag: function (data, tag) { // 移除默认添加的临时标签,替换为自定义的两个标签 data.pop(); data.push({ id: "test1_"+tag.text, text: "test1_"+tag.text, newTag: "R" }); data.push({ id: "test2_"+tag.text, text: "test2_"+tag.text, newTag: "W" }); } });
说明
- 方案1适用于需要让用户选择两个生成标签中某一个的场景,选中后标签会正常显示在输入框内。
- 方案2适用于输入文本后直接添加两个标签的场景,无需用户手动选择下拉选项。
内容的提问来源于stack exchange,提问作者lausent
相关产品推荐
相关产品推荐

