如果我们需要调用别的 js文件。怎么处理?
看随机抽取这个例子。在一个页面中如下:
<html>
<head>
<title>random number</title>
<script type="text/javascript">
var errorString = "Please input a positive integer.";
var arr = ["A", "B", "C", "D"];
function count() {
max = arr.length; //max, 全局变量
document.getElementById("num").innerHTML = arr[parseInt(max * Math.random())];
}
function start()
{
timeId = setInterval("count();", 100);
}
function stop() {
clearInterval(timeId);
}
</script>
</head>
<body>
<form>
<input type="button" style='font-size:40px' value="Start" οnclick="start()">
<input type="button" style='font-size:40px' value="Stop" οnclick="stop();">
</form>
<br>
<font color="blue" style='font-size:150px' id="num"></font>
<br>
</body>
</html>
我们可以把js放在另外一个文件里,比如当前文件夹的 a.js 中。
这样html页面如下:
<html>
<head>
<title>random number</title>
<script type="text/javascript" src="a.js">
</script>
</head>
<body>
<form>
<input type="button" style='font-size:40px' value="Start" οnclick="start()">
<input type="button" style='font-size:40px' value="Stop" οnclick="stop();">
</form>
<br>
<font color="blue" style='font-size:150px' id="num"></font>
<br>
</body>
</html>
a.js
var errorString = "Please input a positive integer.";
var arr = ["A", "B", "C", "D"];
function count() {
max = arr.length; //max, 全局变量
document.getElementById("num").innerHTML = arr[parseInt(max * Math.random())];
}
function start()
{
timeId = setInterval("count();", 100);
}
function stop() {
clearInterval(timeId);
}
这样就行了。
当然,也可以把 a.js放在web上,然后引用成下面这样。
<html>
<head>
<title>random number</title>
<script type="text/javascript" src="http://localhost:8080/test/js/random1.js"></script>
</head>
<body>
<form>
<input type="button" style='font-size:40px' value="Start" οnclick="start()">
<input type="button" style='font-size:40px' value="Stop" οnclick="stop();">
</form>
<br>
<font color="blue" style='font-size:150px' id="num"></font>
<br>
</body>
</html>
HTML调用Js文件
最新推荐文章于 2023-12-27 21:39:34 发布