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

如何不修改源文件重写Select2的selectionContainer原型方法

重写Select2 4.1.0-rc.0版本多选选中项容器方法的方案

问题背景

你使用的基于jQuery的Select2 4.1.0-rc.0版本中,多选场景下选中项的容器由MultipleSelection.prototype.selectionContainer方法生成,原始方法代码如下:

MultipleSelection.prototype.selectionContainer = function () {
  var $container = $(
    '<li class="select2-selection__choice">' +
      '<button type="button" class="select2-selection__choice__remove" ' +
      'tabindex="-1">' +
        '<span aria-hidden="true">&times;</span>' +
      '</button>' +
      '<span class="select2-selection__choice__display"></span>' +
    '</li>'
  );

  return $container;
};

需求为在不修改原始库文件的前提下,更改或重写该方法。

实现方法

Select2的所有实例方法都挂载在对应构造函数的原型上,你只需要在加载完Select2库文件之后、初始化任何Select2实例之前,覆盖该原型方法即可,完全不需要改动库源码。
通用兼容写法(适配所有引入方式):

// 该段代码需放在select2.js引入语句之后执行
$.fn.select2.amd.require('select2/selection/multiple', function (MultipleSelection) {
  // 直接覆盖原型上的selectionContainer方法
  MultipleSelection.prototype.selectionContainer = function () {
    // 在这里自定义你需要的选中项容器结构、类名、内部元素即可
    var $container = $(
      '<li class="select2-selection__choice your-custom-class">' +
        '<button type="button" class="select2-selection__choice__remove" ' +
        'tabindex="-1">' +
          '<span aria-hidden="true">&times;</span>' +
        '</button>' +
        '<span class="select2-selection__choice__display"></span>' +
      '</li>'
    );
    return $container;
  };
});

注意事项

  • 执行顺序不能错:必须先引入jQuery、再引入Select2库文件、再执行上述重写代码,最后再执行$('你的选择器').select2(你的配置)初始化逻辑,否则重写不会对已初始化的实例生效。
  • 如果你是通过非模块化方式直接在页面引入Select2的全局版本,也可以直接在全局找到MultipleSelection构造函数后直接覆盖原型方法,但通过Select2内置的AMD模块加载器获取构造函数是最稳妥的兼容写法,不会因为版本调整全局变量挂载逻辑失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 19:06:32