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

在Thymeleaf中运行JS脚本报错:$(...).datepicker is not a function

解决Thymeleaf中Datepicker报错:$(...).datepicker is not a function

嘿,这个问题我之前也踩过坑!咱们拆解一下错误原因再一步步解决:

错误核心原因

你看到的Uncaught TypeError本质是两个问题叠加:

  1. 你用的是jQuery Slim版本:这个版本为了轻量化,砍掉了datepicker组件依赖的部分核心方法(比如$.fn.extend),导致组件无法正常绑定。
  2. 缺少Datepicker的依赖库:datepicker不是jQuery原生自带的功能,它要么是jQuery UI的组件,要么是Bootstrap Datepicker这类第三方插件,你没引入对应的库自然调用不了。

具体解决步骤

1. 替换jQuery Slim为完整版本

把你当前的Slim版jQuery换成完整的标准版本,比如:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

2. 引入Datepicker对应的组件库

根据你项目的技术栈选一种:

选项A:用jQuery UI Datepicker(通用场景)

需要引入jQuery UI的CSS和JS文件:

<!-- jQuery UI 样式文件 -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<!-- jQuery UI 核心JS -->
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

选项B:用Bootstrap Datepicker(如果项目用Bootstrap)

除了Bootstrap本身的CSS/JS,还要加datepicker的专属样式和脚本:

<!-- Bootstrap 样式 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
<!-- Bootstrap Datepicker 样式 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
<!-- Bootstrap Datepicker JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>

3. 严格遵守加载顺序

必须按这个顺序引入脚本/样式,不然还是会报错:

完整jQuery → 框架依赖(Bootstrap/JQuery UI)→ Datepicker组件 → 你的自定义Thymeleaf内联JS

4. 完整示例代码(以jQuery UI为例)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Datepicker 测试</title>
    <!-- 完整jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <!-- jQuery UI 样式 -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <!-- jQuery UI JS -->
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
</head>
<body>
    <!-- 要绑定datepicker的输入框 -->
    <input type="text" id="date-picker-input">

    <!-- Thymeleaf内联JS -->
    <script th:inline="javascript">
        $(document).ready(function() {
            // 初始化datepicker
            $('#date-picker-input').datepicker();
        });
    </script>
</body>
</html>

额外检查点

  • 别重复引入jQuery:如果页面其他地方已经加过jQuery,要确保只有一个完整版本,多个jQuery实例会导致冲突。
  • 检查依赖加载:打开浏览器开发者工具的「Network」标签,确认所有引入的CSS/JS都成功加载(没有404错误)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:21:08