2014-07-15 129 views
1

我想要使用一个外部JavaScript文件中thymeleaf项目,所以我做了以下内容:thymeleaf:外部JS文件

这是文件的声明方式(我把此之前/身体在许多其他职位)建议

<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"); 

}; 

但是,我从萤火虫中收到以下错误“Uncaught ReferenceError:change2 is not defined”。

我也试过

function change2() { 

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

}; 

和我得到“遗漏的类型错误:不能为空的设置属性‘的className’”

好像js文件甚至没有processed.any解?

在此先感谢

+1

好像change2功能在外部脚本之前烧制中完全负载。你可以使用onload处理程序来调用change2来修复它。看到这个:http://stackoverflow.com/questions/3842614/how-do-i-call-a-javascript-function-on-page-load – Rooster

回答

1

我建议你使用的事件处理程序,而不是在href属性的函数调用。 所以,你可能会改变你的锚连结此:

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

要添加一个点击事件,你必须利用提出了window.onload事件为鸡。

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

您可以查看此工作示例:http://jsfiddle.net/RKSZ2/1/

+0

谢谢!看来,整个问题是document.getElementById(“ l1“)。setAttribute(”class“,”“);删除甚至我的代码working.so是否有另一种方法使元素没有类? – Ronnie147

+0

我不太明白你的问题,但是,如果在dom中没有id =“I1”的元素,那么这个document.getElementById(“l1”)将返回null和document.getElementById(“l1”) .setAttribute(“class”,“”);将是一个无效的命令。在删除一个元素的类之前,你应该检查该元素是否存在于dom中。另外一个小的评论是,该类应该以这种方式删除http://stackoverflow.com/a/2155786/3414905,以避免删除其他类,这个元素可能有。 – Nickey