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

JS表格日历无法显示 报Unexpected token '('、Identifier expected错误

问题原因

两个报错均由代码语法错误、逻辑错误共同导致,具体问题点如下:

  • 核心语法错误:所有document.getElementById.("xxx")写法中,方法名和参数括号之间多写了一个.,不符合JavaScript语法规则,这直接触发VS Code的Identifier expected. ts(1003)提示,以及浏览器控制台的Uncaught SyntaxError: Unexpected token '('报错。
  • 语法+逻辑错误:new Date(August, 2022)、new Date(September, 2022)写法完全无效,August、September属于未定义的标识符,直接引用会触发运行时错误;且你需要对比的是当前月份的数字值,不需要创建Date实例存储月份。
  • 事件绑定逻辑错误:window.onload = getDate();写法错误,加括号会让JS在解析到该行时立即执行getDate函数,此时页面DOM元素还未加载完成,getElementById会获取不到表格元素返回null,后续设置style属性时还会触发空值报错。
  • 样式逻辑遗漏:没有给所有月份表格设置默认隐藏样式,会导致页面加载后所有月份日历同时展示。
修正方案
  1. 删除所有getElementById和后续参数括号之间多余的.
  2. 移除无意义的Date实例创建逻辑,直接用1-12的数字作为月份判断依据
  3. 修正window.onload绑定写法,只传入函数引用,不要加执行括号
  4. 新增全局CSS规则,默认隐藏所有月份表格,仅在匹配到当前月份时展示对应表格
修正后代码

首先在页面head标签内添加样式,默认隐藏所有日历表格:

table {
  display: none;
}

修正后的JavaScript代码如下:

// 绑定函数引用,不要加括号,等DOM加载完成后自动执行
window.onload = getDate;
function getDate() {
  // Date实例的getMonth方法返回0-11的数值(0代表1月,11代表12月),+1后对应自然月数字
  const currentMonth = new Date().getMonth() + 1;
  // 直接匹配月份数字展示对应表格
  if (currentMonth === 7) {
    document.getElementById("july_22").style.display = "table";
  } else if (currentMonth === 8) {
    document.getElementById("august_22").style.display = "table";
  } else if (currentMonth === 9) {
    document.getElementById("september_22").style.display = "table";
  } else if (currentMonth === 10) {
    document.getElementById("october_22").style.display = "table";
  } else if (currentMonth === 11) {
    document.getElementById("november_22").style.display = "table";
  } else if (currentMonth === 12) {
    document.getElementById("december_22").style.display = "table";
  }
  // 1-6月的展示逻辑可以按照上述格式补全
}

你提供的7月表格HTML结构没有问题,只需按照相同结构补全其余月份的表格代码,设置对应id即可正常运行。

内容的提问来源于stack exchange,提问作者Daniel Hernandez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 09:54:29