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

FullCalendar V5跨文件调用方法报calendar.xxx is not a function错误求助

报错原因

你代码中的calendar实例是在DOMContentLoaded回调的局部作用域内声明的,侧边栏点击事件的回调处于全局作用域,无法访问到局部变量calendar,因此调用calendar.render()时会抛出方法不存在的错误。同时你提到的跨文件/跨页面调用方法的需求,在FullCalendar V5中可以通过挂载全局实例的方式实现。

修复代码

JavaScript代码

document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');

    // 把calendar实例挂载到window对象,支持跨作用域、跨文件调用
    window.calendar = new FullCalendar.Calendar(calendarEl, {
      timeZone: 'UTC',
      initialView: 'timeGridWeek',
      headerToolbar: {
        left: 'prev,next today',
        center: 'title',
        right: 'timeGridWeek,timeGridDay'
      },
      events: 'https://fullcalendar.io/demo-events.json'
    });

    calendar.render();
    // 点击事件移到作用域内即可直接访问calendar实例
    $('.icon').click(function(){
      $('.sidebar').toggleClass('in');
      calendar.render();
      // 跨文件/其他位置调用的统一写法:window.calendar.render()
    });
});

CSS代码(无需修改)

.sidebar{
  background:#eeeeee;
  height:100vh;
  width:200px;  
}
.h-100{
  height:100vh!important;
}
.main{
  flex:1;
  padding:20px
}
.icon{
  cursor: pointer;
}
.in{
  width:25px!important;
}

HTML代码(无需修改)

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/fullcalendar-scheduler@5.7.0/main.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/fullcalendar-scheduler@5.7.0/main.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex h-100">
  <div class="sidebar in">
    <div class="icon text-right px-2">
      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-text-left" viewBox="0 0 16 16">
  <path fill-rule="evenodd" d="M2 12.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm0-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5zm0-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm0-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/>
</svg>
    </div>
    
  </div>
  <div class="main">
     <div id='calendar'></div>
  </div>
</div>
跨作用域调用说明

所有需要调用FullCalendar实例方法的位置,都可以直接通过window.calendar访问实例,比如window.calendar.next()切换到下一页、window.calendar.addEvent(eventObj)添加事件等,完全符合V5版本的方法调用规范。

内容的提问来源于stack exchange,提问作者Amal nandan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:57:03