如何在Sortable列表变更时触发函数且避免重复执行?
解决Sortable跨列表拖拽时函数重复触发问题
针对你遇到的同组Sortable列表跨拖拽时函数触发两次的问题,可以通过判断拖拽的目标列表,确保一次拖拽操作只触发一次函数。以下是具体实现:
实现代码
// 定义要触发的业务函数 function handleListChange() { // 这里编写列表变更后的处理逻辑 console.log('列表已完成变更'); } // 标记当前拖拽会话,避免重复触发 let currentDragSession = null; Sortable.create(plansList, { animation: 100, group: 'list-1', draggable: '.recipe', handle: '.handle', sort: true, filter: '.sortable-disabled', chosenClass: 'active', // 拖拽开始时生成唯一会话标识 onStart: () => { currentDragSession = Date.now(); }, // 拖拽结束时判断是否触发函数 onEnd: function(evt) { // 仅当当前列表是拖拽的目标列表时执行 if (evt.to === this.el) { currentDragSession = null; handleListChange(); } } }); Sortable.create(suggestionsList, { animation: 100, group: 'list-1', draggable: '.recipe', handle: '.handle', sort: true, filter: '.sortable-disabled', chosenClass: 'active', onStart: () => { currentDragSession = Date.now(); }, onEnd: function(evt) { if (evt.to === this.el) { currentDragSession = null; handleListChange(); } } });
逻辑说明
- 拖拽会话标记:在
onStart事件中生成唯一的时间戳作为会话标识,标记当前拖拽操作 - 目标列表判断:
onEnd事件中通过evt.to获取拖拽的目标列表,只有当当前实例的列表是目标列表时,才执行业务函数 - 兼容内部排序:内部排序时,
evt.from和evt.to指向同一个列表,条件依然成立,会正常触发函数;跨列表拖拽时,仅目标列表的onEnd会满足条件,确保函数只执行一次
如果你的Sortable版本较旧,事件参数可能存在差异(比如部分旧版本用evt.target代替evt.to),可以根据实际参数调整判断条件。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

