使用JSP的javascript问题

时间:2011-04-10 03:44:03

标签: javascript jsp tomcat6 getelementsbytagname

嘿所有我想在我的jsp文件中使用javascript,如下所示:

JSP文件:

 <?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>title goes here</title>
<link rel="icon" href="scripts/assets/favicon.ico" type="image/x-icon"/>
<%-- 
    Ajax code to refresh the main page's contents.
    This ajax code is specific to the home page not 
    for all so it is kept outside the main script file.
 --%>
<script type="text/javascript" src="scripts/AjaxRefresh.js"></script>
<script type="text/javascript" src="scripts/MainScript.js"></script>
<link rel="stylesheet" type="text/css" href="scripts/MainStyle.css" />

</head>
<body>
<div class="mainContainer">
<div class="header">
header
</div>
<div class="leftNavigation">
<a href="Home" title="Go to Home Page" class="navigationButton" id="home" onclick="animateLink()">Home</a>
<br/>
<a href="Home" title="Go to Home Page" class="navigationButton">Home</a>
<br/>
<a href="Home" title="Go to Home Page" class="navigationButton">Home</a>
<br/>
<a href="Home" title="Go to Home Page" class="navigationButton">Home</a>
<br/>
<a href="Home" title="Go to Home Page" class="navigationButtonActive">Home</a>
<br/>
<a href="Home" title="Go to Home Page" class="navigationButton">Home</a>
<br/>
<a href="Home" title="Go to Home Page" class="navigationButton">Home</a>
<br/>
<a href="Home" title="Go to Home Page" class="navigationButton">Home</a>
</div>
<div class="mainContentArea">
Main Content Area
</div>
<div class="rightTabBar">
Right Tab Bar
</div>
<div class="footer">
Footer
</div>
</div>
</body>
</html>

和MainScript.js文件如下:

window.onload = initAll();

function initAll(){     
    var navigationButton = document.getElementsByTagName("a");
    for ( var int = 0; int < navigationButton.length; int++) {
        if(navigationButton[int].className == "navigationButton")
            navigationButton[int].onclick = animateLink;
    }   
}

function animateLink(){
    this.className = "navigationButtonActive";
    return false;
}

但是当我尝试执行此代码时,我发现javascript代码无法正常工作,并且使用firebug我发现变量navigationBUtton是一个空数组。

其实我来自PHP背景,所以不知道jsp的概念,所以这里有什么问题?

PS:我在ubuntu 10.10平台上使用带有apache tomcat6的eclipse 3.5作为web服务器。

谢谢:)

1 个答案:

答案 0 :(得分:1)

您将函数的结果分配给window.onload,而不是让它指向函数名称。

替换

window.onload = initAll();

通过

window.onload = initAll;

或只是做

window.onload = function() {     
    var navigationButton = document.getElementsByTagName("a");
    for ( var int = 0; int < navigationButton.length; int++) {
        if(navigationButton[int].className == "navigationButton")
            navigationButton[int].onclick = animateLink;
    }   
}

另见:


请注意,此问题与JSP无关。