如何在FullCalendar的eventClick中获取事件ID并展示详情?
FullCalendar点击事件获取ID并展示详情的实现步骤
1. 确保事件数据包含ID字段
从数据库返回的事件数据里,必须包含id属性(对应数据库中事件的主键),同时可以把常用详情字段放在extendedProps里备用,示例数据格式:
// Ajax接口返回的事件数组 [ { id: 1, title: "项目评审会", start: "2024-05-22T09:00:00", end: "2024-05-22T11:00:00", extendedProps: { description: "讨论Q2项目进度与风险", location: "3楼会议室" } } ]
2. 用eventClick回调捕获点击事件
在FullCalendar初始化配置中,添加eventClick回调函数,它会接收一个info参数,里面包含被点击的完整事件对象,直接从中提取ID和详情即可:
document.addEventListener('DOMContentLoaded', function() { const calendarEl = document.getElementById('calendar'); const calendar = new FullCalendar.Calendar(calendarEl, { // 基础配置(视图、时区等) initialView: 'dayGridMonth', // Ajax加载事件数据 events: '/api/get-events', // 点击事件触发的回调 eventClick: function(info) { // 1. 获取事件ID const eventId = info.event.id; // 方式一:直接用事件对象里已有的详情展示 const detailHtml = ` <p>事件ID:${eventId}</p> <p>标题:${info.event.title}</p> <p>时间:${info.event.start.toLocaleString()} 至 ${info.event.end?.toLocaleString()}</p> <p>地点:${info.event.extendedProps.location}</p> <p>详情:${info.event.extendedProps.description}</p> `; // 可以把内容插入模态框或页面指定区域 $('#eventDetailModal .modal-body').html(detailHtml); $('#eventDetailModal').modal('show'); // 方式二:如果详情数据未提前加载,发起Ajax请求获取 /* $.ajax({ url: '/api/get-event-detail', method: 'GET', data: { id: eventId }, success: function(res) { // 渲染详情到页面 $('#detailContainer').html(` <h3>${res.title}</h3> <p>ID:${res.id}</p> <p>详情:${res.description}</p> `); }, error: function() { alert('获取详情失败'); } }); */ // 阻止默认跳转(如事件链接的默认行为) info.jsEvent.preventDefault(); } }); calendar.render(); });
关键注意点
- 必须保证事件数据中的
id字段存在,FullCalendar会自动绑定这个属性到事件对象上 - 额外的详情字段统一放在
extendedProps中,避免和FullCalendar内置字段冲突 - 展示详情的载体可以是Bootstrap模态框、自定义弹窗或页面内的固定区域,根据业务场景选择
内容的提问来源于stack exchange,提问作者see
相关产品推荐
相关产品推荐

