JavaScript报错uncaught ReferenceError: tgl is not defined求助
问题原因及解决方法
报错原因
- 变量作用域限制:你在
select回调函数里用var tgl声明变量,这个变量是回调函数的局部变量,只能在函数内部访问,外部的HTML脚本根本拿不到它,所以会报tgl is not defined。 - 执行时机不匹配:HTML里的
<script>document.write(tgl)</script>是页面加载时就执行的,而select回调是用户点击日历选择日期后才触发的——这时候页面早就加载完了,document.write早就执行过,就算tgl是全局变量,这时候也还没被赋值,照样会报错,而且document.write在页面加载完成后使用还会覆盖整个页面,非常不建议用。
解决方法(推荐方案)
直接在select回调里修改模态框的标题内容,不用依赖全局变量,也避免document.write的问题:
第一步:修改JavaScript代码
document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { selectable: true, selectHelper: true, select: function(start, end, alldays){ // 格式化选中的日期 var selectedDate = moment(start).format('DD-MM-YYYY'); // 直接更新模态框标题的文本 document.getElementById('exampleModalLabel').textContent = selectedDate; // 打开模态框 $("#BookingModal").modal('toggle'); } }); calendar.render(); });
第二步:修改HTML部分
把原来带script的标题改成普通的静态标题(可以留空或写默认提示):
<h1 class="modal-title fs-5" id="exampleModalLabel">选择的日期</h1>
备选方案(不推荐,仅作理解作用域用)
如果一定要用全局变量,需要在函数外部提前声明,然后在回调里赋值,最后同样通过DOM操作更新标题(别用document.write):
// 在全局作用域声明变量 var tgl; document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { selectable: true, selectHelper: true, select: function(start, end, alldays){ $("#BookingModal").modal('toggle'); // 直接给全局变量赋值,不要加var tgl = moment(start).format('DD-MM-YYYY'); // 更新模态框标题 document.getElementById('exampleModalLabel').textContent = tgl; } }); calendar.render(); });
内容的提问来源于stack exchange,提问作者Morion
相关产品推荐
相关产品推荐

