如何让jQuery左右布局multi-select多选组件的搜索功能正常运行
现有代码问题修复
问题出在两处:
- 你在搜索框header中额外加了
<br>标签,导致that.$selectableUl.prev()取到的是<br>节点而非搜索输入框,无法绑定搜索事件 - 初始化代码没有包裹在DOM加载完成的回调中,可能出现组件还没渲染完成就执行绑定逻辑的问题
修复后的JS代码如下:
// 包裹在DOM就绪回调中 $(function() { $('.searchable').multiSelect({ // 去掉多余的<br>标签 selectableHeader: "<input type='text' class='search-input form-control form-control-sm' autocomplete='off' placeholder='Search..'>", selectionHeader: "<input type='text' class='search-input form-control form-control-sm' autocomplete='off' placeholder='Search..'>", afterInit: function(ms) { var that = this, // 稳妥写法:直接在header容器内找搜索输入框,避免节点顺序问题 $selectableSearch = that.$selectableUl.parent().find('.search-input'), $selectionSearch = that.$selectionUl.parent().find('.search-input'), selectableSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selectable:not(.ms-selected)', selectionSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selection.ms-selected'; that.qs1 = $selectableSearch.quicksearch(selectableSearchString) .on('keydown', function(e) { if (e.which === 40) { that.$selectableUl.focus(); return false; } }); that.qs2 = $selectionSearch.quicksearch(selectionSearchString) .on('keydown', function(e) { if (e.which == 40) { that.$selectionUl.focus(); return false; } }); }, afterSelect: function() { this.qs1.cache(); this.qs2.cache(); }, afterDeselect: function() { this.qs1.cache(); this.qs2.cache(); } }); })
如果修改后还是失效,可直接替换quicksearch逻辑,手写搜索过滤避免依赖年久失修的库:
// 把原来的quicksearch绑定逻辑替换为自定义实现即可 $selectableSearch.on('input', function() { const keyword = $(this).val().trim().toLowerCase() $(selectableSearchString).each(function() { $(this).toggle($(this).text().toLowerCase().includes(keyword)) }) }) $selectionSearch.on('input', function() { const keyword = $(this).val().trim().toLowerCase() $(selectionSearchString).each(function() { $(this).toggle($(this).text().toLowerCase().includes(keyword)) }) })
符合要求的现代化替代方案
核心需求是点击选项直接左右转移、无需额外按钮、支持搜索,可根据你的技术栈选择对应方案:
- Vue生态:可以用element-plus的Transfer穿梭框组件,开启
filterable属性即可实现搜索,默认支持点击选项直接转移 - React生态:可以用antd的Transfer穿梭框组件,开启
showSearch属性即可实现搜索,同样支持点击直接选中转移 - 无框架/通用jQuery场景:可以用Slim Select组件,内置搜索功能、支持左右布局多选,配置项简单维护活跃,不需要额外依赖其他搜索库
内容的提问来源于stack exchange,提问作者Stig Kølbæk
相关产品推荐
相关产品推荐

