You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Thymeleaf内联JavaScript被完全忽略的问题求助

Thymeleaf内联JavaScript被完全忽略的问题求助

各位大佬好,我刚接触Spring Boot和Thymeleaf,最近遇到个头疼的问题:我想在Thymeleaf视图里加一段基础的原生JS脚本,但它完全被忽略了——检查页面元素根本看不到这段脚本,控制台还提示找不到对应的函数。我猜问题可能和这个视图用了布局模板有关,但就是找不到问题出在哪,麻烦大家帮我看看!

我的视图代码:

<!doctype html>
<html th:replace="~{fragments/layout :: layout(~{::title}, ~{}, ~{}, ~{::main})}">
<head>
<title>Reports Page</title>
</head>
<body>
<main role="main" class="flex-shrink-0">
<!-- some HTML code here -->
<select class="form-select" id="year" aria-label="Year dropdown" th:onchange="reloadPage()">
<option
th:each="yearRow : ${years}"
th:value="${yearRow}"
th:selected="(${yearRow} == ${year})"
th:text="${yearRow}">
</option>
</select>
<!-- other HTML code here -->
</main>

<script th:inline="javascript" type="text/javascript">
function reloadPage() {
alert("You selected a year");
}
</script>
</body>
</html>

布局片段代码:

<!DOCTYPE html>
<html class="h-100" th:fragment="layout (title, css_assets, js_assets, content)" xmlns:th="http://www.thymeleaf.org">
<head>
<!-- Usual head stuff - meta tags, links to Bootstrap CSS & fonts libraries etc -->
<!-- Common CSS Styles -->
<link rel="stylesheet" th:href="@{/css/styles.css}">
<!-- Per-page placeholder for additional links -->
<th:block th:replace="${css_assets}" />
<title th:replace="${title}">Layout Title</title>
</head>
<body class="d-flex flex-column h-100">
<header th:replace="~{fragments/header :: header}"></header>
<div th:replace="${content}">
<p>Layout content</p>
</div>
<footer th:replace="~{fragments/footer :: footer}"></footer>

<!-- Common scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<!-- Per-page placeholder for additional scripts -->
<th:block th:replace="${js_assets}" />
</body>
</html>

问题现象:

  • 检查页面源码时,完全看不到这段内联的<script>代码
  • 控制台调用reloadPage()函数时,提示函数未找到

我知道可能可以通过布局里的${js_assets}参数从外部JS文件注入函数,但我就是搞不懂为什么内联写法不行,是不是我漏了什么关键的语法或者配置?麻烦各位指点一下,谢谢啦!

备注:内容来源于stack exchange,提问作者Valentin Vucea

火山引擎 最新活动