javascript - thymeleaf:外部js文件

标签 javascript thymeleaf

我正在尝试在 thymeleaf 项目中使用外部 javascript 文件,因此我执行了以下操作:

这就是文件的声明方式(我将其放在/body 之前,正如许多其他帖子中所建议的那样)

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

这是 html 函数调用

<a id="l2" th:href="'javascript:change2();'">

这是js文件

function change1() {
 document.getElementById("l1").setAttribute("class", "selected");
 document.getElementById("l2").setAttribute("class", "");

};


function change2() {

 document.getElementById("l1").setAttribute("class", "");
 document.getElementById("l2").setAttribute("class", "selected");

};

但是我从 firebug 收到以下错误“Uncaught ReferenceError:change2 未定义”。

我也尝试过

function change2() {

document.getElementById("l1").className="";
document.getElementById("l2").className="selected";

};

我收到“未捕获的类型错误:无法将属性“className”设置为 null”

似乎js文件没有被处理。有什么解决办法吗?

提前致谢

最佳答案

我建议您在 href 属性上使用事件处理程序而不是函数调用。 因此,您可以将 anchor 链接更改为:

<a id="l2" href="javascript:void(0);">l2_Link</a>

要添加点击事件,您必须按照 Rooster 的建议使用 window.onload 事件。

window.onload = function (){
    document.getElementById ("l2").addEventListener ("click", change2, false);
}

您可以在以下位置查看此操作的工作示例:http://jsfiddle.net/RKSZ2/1/

关于javascript - thymeleaf:外部js文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24761382/

相关文章:

javascript - 简单的 JavaScript 游戏

spring-boot - 升级 Spring 和 thymeleaf 打破了我的授权

java - Spring boot Thymeleaf 根据其他下拉列表选择填充下拉列表

javascript - Spring和Thymeleaf : How to move javascript to a separate . js文件

spring - Thymeleaf:消息作为另一个消息的参数

javascript - 更新字符串的数组比较函数

javascript - onkeypress vs oninput 如何两全其美

javascript - 为什么 javascript getMonth 从 0 开始计数,而 getDate 从 1 开始计数?

javascript - 如何按值对对象进行排序

java - 将 Thymeleaf 中的当前日期发送到变量