以编程方式更改 fullcalendar 4 的日期

Programmatically change date of fullcalendar 4

我正在使用 fullcalendar v4。我有一个迷你日历,点击一个事件后,我想要另一个更大的日历 (calendar_full) 去那个日期。

<script type="text/javascript">

document.addEventListener('DOMContentLoaded', function() {

    var calendar1 = document.getElementById('calendar_mini');

    var calendar_mini = new FullCalendar.Calendar(calendar1, {
        plugins: ['interaction', 'dayGrid'],
        eventClick: function(info) {

            //when clicking on events, go to date on main calendar
            calendar.gotoDate(info.event.start)


        }
 ...
});

document.addEventListener('DOMContentLoaded', function() {

    var calendar_full = document.getElementById('calendar_full');

    var calendar = new FullCalendar.Calendar(calendar_full, {
         plugins: ['interaction', 'resourceDayGrid', 'resourceTimeGrid', 'timeGrid'],
         header: {
            right: 'prevYear,prev,next,nextYear,today',
            left: 'title',
            center: 'resourceTimeGridDay,resourceTimeGridWeek,resourceDayGridMonth'
            },
           selectMirror: true,
 ...
)};

在 calendar_mini 代码中,calendar.gotoDate(info.event.start) 的 eventClick 函数不会更改主日历。我收到错误:

Uncaught ReferenceError: calendar is not defined

问题是当您在回调中使用名为 "calendar" 的变量时,它不在范围内,这就是它未定义的原因。它的范围仅限于您声明它的 "DOMContentLoaded" 回调。

现在,您在这里不需要两个单独的 "DOMContentLoaded" 回调。对于页面加载时需要 运行 的所有代码,一个通常就足够了。

如果将所有内容都移动到单个回调中,就不会有问题:

document.addEventListener('DOMContentLoaded', function() {

  var calendar1 = document.getElementById('calendar_mini');

  var calendar_mini = new FullCalendar.Calendar(calendar1, {
    plugins: ['interaction', 'dayGrid'],
    eventClick: function(info) {
        //when clicking on events, go to date on main calendar
        calendar.gotoDate(info.event.start)
    }

  var calendar_full = document.getElementById('calendar_full');

  var calendar = new FullCalendar.Calendar(calendar_full, {
     plugins: ['interaction', 'resourceDayGrid', 'resourceTimeGrid', 'timeGrid'],
     header: {
        right: 'prevYear,prev,next,nextYear,today',
        left: 'title',
        center: 'resourceTimeGridDay,resourceTimeGridWeek,resourceDayGridMonth'
        },
       selectMirror: true,
  ...
)};