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

如何在FullCalendar中实现页面刷新后事件保持修改状态

Hey there! The problem you're running into is that your events are hardcoded as static data right now—every time you refresh the page, the script reloads that initial array, so any drag/resizing changes get lost. Let's fix this with a straightforward frontend persistence solution first, then touch on production-ready backend options.

Why Changes Don't Stick

Your current events array is defined directly in the script, which means it's reinitialized from scratch on every page load. To preserve edits, we need to store the updated event data somewhere that persists between sessions.

Frontend Fix (Using localStorage)

You don't need to create new files—just modify your existing <script> block. Here's how to implement it:

  1. Load saved events from localStorage on page load (fall back to your initial events if nothing is saved)
  2. Listen for event modifications (drag, resize, etc.) and save the updated event list to localStorage
  3. Initialize the calendar with the loaded event data

Here's your updated full code with these changes:

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8' />
  <link href='fullcalendar.css' rel='stylesheet' />
  <script src='moment.min.js'></script>
  <script src='jquery.min.js'></script>
  <script src='fullcalendar.js'></script>
  <script>
    $(document).ready(function() {
      // Step 1: Load saved events from localStorage, or use initial data
      const savedEvents = localStorage.getItem('fullCalendarEvents');
      const initialEvents = [
        { title: 'Meeting', start: '2018-05-15T10:30:00', end: '2018-05-15T12:30:00' },
        { title: 'Lunch', start: '2018-05-15T12:00:00' },
        { title: 'Meeting', start: '2018-05-15T14:30:00' },
        { title: 'Tea Hour', start: '2018-05-15T17:30:00' },
      ];
      const events = savedEvents ? JSON.parse(savedEvents) : initialEvents;

      $('#calendar').fullCalendar({
        defaultDate: '2018-05-15',
        selectable: true,
        editable: true,
        events: events,

        // Step 2: Save events when they're dragged to a new date
        eventDrop: function(event, delta, revertFunc) {
          saveEvents();
        },

        // Save events when they're resized
        eventResize: function(event, delta, revertFunc) {
          saveEvents();
        },

        // Optional: Uncomment to add title editing on click
        // eventClick: function(event) {
        //   const newTitle = prompt('Enter new title:', event.title);
        //   if (newTitle) {
        //     event.title = newTitle;
        //     $('#calendar').fullCalendar('updateEvent', event);
        //     saveEvents();
        //   }
        // }
      });

      // Helper function to save current events to localStorage
      function saveEvents() {
        const currentEvents = $('#calendar').fullCalendar('clientEvents');
        // Convert events to a plain object array (strip FullCalendar's internal properties)
        const eventsToSave = currentEvents.map(event => ({
          title: event.title,
          start: event.start.format(),
          end: event.end ? event.end.format() : null
        }));
        localStorage.setItem('fullCalendarEvents', JSON.stringify(eventsToSave));
      }
    });
  </script>
  <style>
    body {
      margin: 40px 10px;
      padding: 0;
      font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
      font-size: 14px;
    }
    #calendar {
      max-width: 800px;
      margin: 0 auto;
    }
  </style>
</head>
<body>
  <div id='calendar'></div>
</body>
</html>

Key Parts Explained:

  • localStorage: A browser-built-in storage that keeps data even after the page is closed/refreshed. We use JSON.parse/JSON.stringify because localStorage only stores strings.
  • eventDrop & eventResize: FullCalendar callback functions that trigger when you drag an event to a new date or resize its duration. We call our saveEvents helper here to persist changes.
  • clientEvents: This method fetches all current events from the calendar instance, which we convert to a plain object (removing FullCalendar's internal properties) before saving.

Production-Grade Backend Solution

If you need this to work across multiple users/devices, you'll want to use a backend database (like MySQL, PostgreSQL, or MongoDB) and API endpoints:

  1. On page load: Fetch events from your backend API instead of localStorage
  2. On event modification: Send an AJAX request to your backend to update the event in the database
  3. On page refresh: The calendar will load the updated events from the API

Example snippet for backend integration (replacing localStorage logic):

// Load events from backend on init
$.get('/api/events', function(events) {
  $('#calendar').fullCalendar({
    // ... other options
    events: events,
    eventDrop: function(event) {
      $.ajax({
        url: `/api/events/${event.id}`,
        method: 'PUT',
        data: {
          title: event.title,
          start: event.start.format(),
          end: event.end ? event.end.format() : null
        },
        success: function() {
          console.log('Event saved to server!');
        }
      });
    }
  });
});

This way, changes are stored permanently on a server and accessible from any device.

内容的提问来源于stack exchange,提问作者abhi lad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:52:25