FullCalendar v4重复绑定致批量删/重复插入问题求助
解决FullCalendar v4重复绑定事件导致的批量删除/重复插入问题
看起来你遇到的核心问题是事件监听重复绑定——每次点击事件时,你都给#deleteButton和#annuleer添加了新的点击处理函数,却没有移除旧的。这就导致点击N次事件后,删除按钮上会堆积N个监听逻辑,触发时就会执行N次删除操作;插入操作也大概率是因为同样的重复绑定问题被多次调用。另外calendar.unselect()无效是因为它只是取消选中状态,根本没解决监听叠加的核心问题。
修复方案:分离事件绑定,用全局变量存储当前选中事件
我们可以把删除和取消按钮的点击监听移到eventClick外面,只绑定一次,同时用一个变量来保存当前选中的事件,从根源上避免重复触发的情况。
// 全局变量存储当前选中的事件 let currentSelectedEvent = null; // 初始化FullCalendar的配置 document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { // 其他日历配置项... eventClick: function(info) { currentSelectedEvent = info.event; // 保存当前选中的事件 $.ajax({ url:"select.php", type:"POST", data: { id: currentSelectedEvent.id }, success: function(data) { console.log(data); $("#exampleModal1").modal(); document.getElementById("title1").value = data['title']; document.getElementById("trainer1").value = data['trainer']; } }); } }); calendar.render(); // 删除按钮的监听:只绑定一次,使用全局变量里的当前事件 $('#deleteButton').on('click', function(){ if (!currentSelectedEvent) return; // 没有选中事件时不执行 $.ajax({ url:"delete.php", type:"POST", data: { id: currentSelectedEvent.id }, success: function() { $('#exampleModal1').modal('hide'); calendar.refetchEvents(); currentSelectedEvent = null; // 清空选中的事件,避免误用 } }); }); // 取消按钮的监听:同样只绑定一次 $('#annuleer').on('click', function(){ $('#exampleModal1').modal('hide'); calendar.unselect(); currentSelectedEvent = null; // 清空选中的事件 }); });
关键改动说明:
- 全局变量存储当前事件:用
currentSelectedEvent保存每次点击的事件,避免在eventClick内部重复绑定监听时捕获不同的event实例。 - 监听移到外部:删除和取消按钮的点击逻辑只初始化一次,不会随着每次
eventClick重复添加,彻底解决多次触发的问题。 - 清空选中状态:在删除或取消后清空
currentSelectedEvent,避免下次操作时误用旧的事件数据。
额外建议:
如果你的模态框是动态生成的(比如每次点击事件才创建),可以用事件委托来绑定监听,确保不管模态框什么时候生成,监听都能生效,同时也不会重复绑定:
$(document).on('click', '#deleteButton', function(){ // 逻辑和上面一致,使用currentSelectedEvent即可 });
内容的提问来源于stack exchange,提问作者RoyBerner
相关产品推荐
相关产品推荐

