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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:39:28