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

jQuery实现两个select标签间列表项双向移动失效问题

解决双向Select双击移动失效问题

我设置了两个带multiple属性的select元素,id分别为list1和list2,list1初始包含若干option选项。预期实现:双击list1中的选项时,该选项从list1移除并添加到list2;双击list2中的选项时,该选项移回list1。但目前仅能实现从list1到list2的移动,反向移动无法生效。

原代码

HTML代码

<select multiple="multiple" id="list1">
    <option value="banana">banana</option>
    <option value="orange">orange</option>
    <option value="apricot">apricot</option>
    <option value="lemon">lemon</option>
</select>
<select multiple="multiple" id="list2">
</select>

jQuery代码

$(function () {
    $("#list1 option").dblclick(function () {
        $("#list1 option:selected").remove().appendTo("#list2");
    });
    $("#list2 option").dblclick(function () {
        $("#list2 option:selected").remove().appendTo("#list1");
    });
});

问题原因

页面初始化时list2中没有任何option元素,直接给#list2 option绑定双击事件的话,这个事件只会绑定到当时存在的元素上。后续从list1移过来的option是动态添加的,不会继承之前绑定的事件,所以双击list2里的选项没有反应。

修复方案

使用jQuery的事件委托机制,把事件绑定到始终存在的父元素(#list1和#list2)上,监听子元素option的双击事件。同时可以把$("#list1 option:selected")替换为$(this),因为双击的就是当前操作的选项,更精准。

修改后的jQuery代码:

$(function () {
    // 给list1绑定事件委托,作用到内部的option
    $("#list1").on("dblclick", "option", function () {
        $(this).remove().appendTo("#list2");
    });
    // 给list2绑定事件委托,覆盖动态添加的option
    $("#list2").on("dblclick", "option", function () {
        $(this).remove().appendTo("#list1");
    });
});

说明

事件委托利用了事件冒泡原理,父元素会监听子元素触发的事件,不管子元素是初始存在还是动态生成的,都能触发对应的处理逻辑,完美解决动态元素的事件绑定问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:31:05