使用FullCalendar开发预约系统时遇Uncaught TypeError错误求助
FullCalendar 选中日期报错及多日期选中展示解决方案
错误原因
你遇到的Uncaught TypeError: start.getDate is not a function是因为FullCalendar v5+版本的select回调第一个参数不是Date对象,而是一个包含start、end等属性的SelectionInfo对象。直接对这个对象调用Date方法自然会报错。
另外你的代码还有两处语法错误:
select回调里的date: date.getDate();和backgroundColor: 'green';是无效语法,不符合JS赋值或配置规则- 初始化Calendar时结尾的括号与大括号写反(
);应改为});)
修正后的完整实现
以下是实现「多选日期展示+取消选中」的完整代码,包含错误修复和功能落地:
<!-- 页面需添加展示选中日期的容器 --> <div id="selectedDates"></div> <div id="calendar"></div> <script> // 用Set存储选中日期的字符串格式,避免Date对象引用问题 let selectedDates = new Set(); const selectedDatesEl = document.getElementById('selectedDates'); const calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { headerToolbar: { start: 'title', center: '', end: '' }, initialView: 'dayGridMonth', selectable: true, // 设置选中日期的默认样式 selectStyle: { backgroundColor: 'green' }, select: function(info) { // 获取选中的起始日期(单个日期选中时,start与end为同一天) const selectedDate = info.start; // 转成YYYY-MM-DD格式字符串,方便存储和比对 const dateStr = selectedDate.toISOString().split('T')[0]; // 切换选中状态:已选中则移除,未选中则添加 if (selectedDates.has(dateStr)) { selectedDates.delete(dateStr); calendar.unselect(); // 同步取消日历上的选中样式 } else { selectedDates.add(dateStr); } // 更新页面的选中日期展示 renderSelectedDates(); // 控制台打印正确的选中集合 console.log('已选中日期:', Array.from(selectedDates)); } }); calendar.render(); // 渲染选中日期到页面容器的函数 function renderSelectedDates() { if (selectedDates.size === 0) { selectedDatesEl.innerHTML = '<p>暂无选中日期</p>'; return; } // 生成带取消按钮的日期项 const dateItems = Array.from(selectedDates).map(dateStr => ` <span class="date-item"> ${dateStr} <button onclick="removeSelectedDate('${dateStr}')">×</button> </span> `).join(''); selectedDatesEl.innerHTML = `<p>已选中日期:</p>${dateItems}`; } // 手动移除单个选中日期的函数 function removeSelectedDate(dateStr) { selectedDates.delete(dateStr); renderSelectedDates(); } </script> <style> .date-item { display: inline-block; margin: 0 8px 8px 0; padding: 4px 8px; background: #e8f5e9; border-radius: 4px; } .date-item button { margin-left: 6px; border: none; background: transparent; cursor: pointer; color: #f44336; } </style>
关键说明
- 用
Set存储日期字符串,避免Date对象的时间戳干扰,快速判断重复选中 - 通过
info.start获取选中日期,单个日期选中时info.start与info.end值一致 - 调用
calendar.unselect()同步取消日历上的选中样式,保证状态统一 - 额外实现了点击日期项按钮直接取消选中的功能,满足交互需求
内容的提问来源于stack exchange,提问作者upcoming
相关产品推荐
相关产品推荐

