例子:

这行得通

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" 
      xmlns:th="http://www.thymeleaf.org"> 
<head lang="en"> 
    <meta charset="UTF-8"/> 
    <title></title> 
</head> 
<body> 
    <button th:onclick="'javascript:sayHello(\'hello\')'">Say Hello</button> 
</body> 
 
<script> 
    function sayHello(text) { 
        alert(text); 
    } 
</script> 
</html> 

但是,如果我将 js 移动到同一文件夹中的文件 hello.js,脚本将无法运行。

我试过这样嵌入:

<script type="text/javascript" th:src="@{hello.js}"></script> 

像这样:

<script type="text/javascript" src="hello.js"></script> 

我做错了什么?

请您参考如下方法:

假设你使用的是 Spring Boot 的默认配置,你应该在 src/main/resources/templates/ 中有你的 thymeleaf 文件,所以你应该将 javascript 文件放在:

/src/main/resources/static 

说明:您的构建工具(Maven 或 Gradle)将复制应用程序类路径中 /src/main/resources/ 中的所有内容,如 Spring Boot's docs 中所写,类路径中名为 /static 的目录中的所有内容都将作为静态内容提供。


这个目录也可以工作,但不鼓励:

/src/main/webapp/ 

Do not use the src/main/webapp directory if your application will be packaged as a jar. Although this directory is a common standard, it will only work with war packaging and it will be silently ignored by most build tools if you generate a jar.


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!