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

Select2多选templateSelection配置后选中统计文本重复显示问题求助

问题根源

你遇到的重复展示问题,是因为templateSelection回调会对每一个选中的选项独立执行一次:选1个就调用1次,选2个就调用2次,所以会输出2条相同的统计文本。

解决方案

你可以通过「仅给第一个选中项返回统计文本、其余选中项返回空值+隐藏空标签」的逻辑实现需求,完整修改后的代码如下:

<!DOCTYPE html>
<html lang="zh-CN" >
<head>
    <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css'>
    <style>
        /* 隐藏空的已选标签 */
        .select2-selection__choice:empty {
            display: none !important;
            padding: 0;
            margin: 0;
        }
    </style>
</head>
<body>
    <select id="idMulti" class="js-example-basic-multiple" style="width: 100%" multiple="multiple">
        <option value="Option 1">选项1</option>
        <option value="Option 2">选项2</option> 
    </select>   
</body>
          
<script src='https://code.jquery.com/jquery-3.5.1.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.js'></script>  

<script>
$(function() {
    $('#idMulti').select2({
      placeholder: '',
      minimumResultsForSearch: -1,
      templateSelection: function (data) {
        if (!data.id) return data.text;
        const selectedList = $('#idMulti').val() || [];
        const total = $('option', $('#idMulti')).length;
        // 只对第一个选中项返回统计文本
        if (data.id === selectedList[0]) {
            // 如果你需要选中1个时显示选项内容而非统计,可替换为下方注释代码
            // return selectedList.length === 1 ? data.text : `已选 ${selectedList.length} / ${total} 项`;
            return `已选 ${selectedList.length} / ${total} 项`;
        }
        // 其余选中项返回空值
        return '';
      }
    });
});
</script>
</html>

如果需要选中1个时显示选项本身的文本、仅选中多个时显示统计,只需要把上面代码中return部分替换为注释里的逻辑即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:15:03