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

Sim*_*ion 7 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");
    };
};
Run Code Online (Sandbox Code Playgroud)

的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>
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 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>
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你的test.js函数有错误.你不应该;在函数声明的最后添加if if/else条件.正确的语法是:

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

要么:

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