如何在.js文件中调用JS函数到.jsp文件中?

时间:2012-07-07 15:07:56

标签: javascript jsp

我试图将... / js / index.js文件中的javaScript函数调用到... / index.jsp文件。

任何建议都会有所帮助。

以下是两个文件中的代码:

index.js

function testing() {

    if ("c" + "a" + "t" === "cat") {
        document.writeln("Same");
    } else {
        document.writeln("Not same");
    };
};

的index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
</head>
<body>

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

       <!-- I want to call testing(); function here -->

    </script>
</body>
</html>

2 个答案:

答案 0 :(得分:18)

首先引用外部index.js文件,然后在内联脚本元素中调用该函数:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
</head>
<body>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript">
       testing();
    </script>
</body>
</html>

顺便说一句,你的test.js函数有错误。您不应该在if / else条件之后放置;,也不应该在函数声明的末尾。正确的语法是:

function testing() {
    if ("c" + "a" + "t" === "cat") {
        document.writeln("Same");
    } else {
        document.writeln("Not same");
    }
}

或:

var testing = function() {
    if ("c" + "a" + "t" === "cat") {
        document.writeln("Same");
    } else {
        document.writeln("Not same");
    }
};

答案 1 :(得分:-2)

你可以这样做

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="js/index.js"></script>
<title>Insert title here</title>
</head>
<body>
<input type = "button" onclick = "javascript:testing()"/>
</body>
</html>

这是最简单的