简体   繁体   English

百里香:外部js文件

[英]thymeleaf:external js file

i'm trying to use an external javascript file in a thymeleaf project so i've done the following: 我试图在thymeleaf项目中使用外部javascript文件,所以我做了以下工作:

this is how the file is declared(i put this just before /body as suggested in many other posts) 这就是文件的声明方式(我将其放在/ body之前,就像其他许多帖子中所建议的那样)

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

this is the html function call 这是html函数调用

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

and this is the js file 这是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");

};

however i get the following error "Uncaught ReferenceError: change2 is not defined" from firebug. 但是我从萤火虫中收到以下错误“ Uncaught ReferenceError:未定义change2”。

i've also tried 我也尝试过

function change2() {

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

};

and i'm getting "Uncaught TypeError: Cannot set property 'className' of null" 并且我收到“未捕获的TypeError:无法将属性'className'设置为null”

it seems like the js file is not even processed.any solution? 似乎js文件甚至没有被处理。任何解决方案?

thanks in advance 提前致谢

I would suggest that you used an event handler instead of a function call on the href attribute. 我建议您使用事件处理程序代替对href属性的函数调用。 So you may change your anchor link to this: 因此,您可以将锚链接更改为此:

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

To add a click event, you have to make use of the window.onload event as Rooster proposed. 要添加click事件,您必须使用Rooster建议的window.onload事件。

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

You can view a working example of this at: http://jsfiddle.net/RKSZ2/1/ 您可以在以下位置查看其工作示例: http : //jsfiddle.net/RKSZ2/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM