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

如何为Select2下拉结果项添加带有效事件的自定义删除按钮?

问题:Select2自定义选项内删除按钮事件绑定失效

项目背景

基于Select2 4.0.13的动态选项创建功能,开发自定义时间窗口范围的UI组件。

需求说明

  • 选择现有条目时,自动填充「start」和「end」小时输入框
  • 用户输入自定义开始/结束小时后,下拉列表显示「Custom Window」
  • 借助Select2的tags功能,命名并保存当前时间窗口设置
  • 待解决问题:无法删除已保存的时间窗口条目

当前UI状态

开发中UI控件

核心问题

为每个选项添加的自定义删除按钮无法绑定有效事件处理程序,点击按钮时Select2仍会触发该选项的选择操作,无法执行删除逻辑。

页面基础标记

<select title="Select your time window here, enter a name to create a new entry." name="time_window_name">
  <option class="internal-option"></option>
  <option value="custom" disabled="disabled" class="internal-option">Custom Window</option>
</select>
  • 空选项作为Select2的「无选择」占位符
  • 「Custom Window」选项用于标识开始/结束时间输入框有值的状态

新增选项后的标记示例

<select title="Select your time window here, enter a name to create a new entry." name="time_window_name">
  [ snip... ]
  <option value="7,8">Morning Rush</option>
  <option value="16,17">Evening Rush</option>
</select>
  • 选项value格式为「startHour,endHour」

Select2初始化配置

{
  allowClear: true,
  placeholder: "no filter",
  tags: true,
  createTag: createTagHandler,
  templateResult: templateResultHandler,
}

结果项渲染函数

function templateResultHandler(state) {
    if (!state.id || ["custom"].includes(state.id)) {
        return state.text;
    }

    const item = $("<div>", {
        class: "select2-result-item d-flex align-items-center",
    });
    $("<span>", {
        class: "select2-result-item__text",
        text: state.text,
    }).appendTo(item);

    const deleteButton = $("<button>", {
        type: "button",
        class: "btn btn-danger btn-sm ms-auto",
    }).appendTo(item);
    $("<i>", {
        class: "fa fa-trash",
    }).appendTo(deleteButton);

    return item;
}
  • select2-result-item类来自网络资源,有效性不确定

已尝试方案

参考过同类问题的解决方案,但未覆盖事件绑定场景;升级示例到4.0.13版本后问题仍存在;另一个方案仅对未选中条目有效,选中条目点击按钮时select2:selecting和select2:select事件均不触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:44:55