0

嘿伙计们,我对代码感到非常沮丧..我正在尝试在我的 html 上调用 .js 文件,但它目前无法正常工作:(我知道代码和一切都是正确的,但它不会执行该功能。你们能看看我的代码是否正确吗?

这是我的 HTML 代码。

<button type="button" onclick="myFunction1()"> Press Me!! </button>
<script type="text/javascript" src="Test2.js"></script>

这是我试图在 html 上调用的 JS 代码:

<!DOCTYPE HTML>
<html>
<head> 
<title> Lab 4 - Task 2.2</title>
<script type = "text/javaScript"> </script>
<p id="demo"</p>
<button onclick="myFunction1()"> Press </button>
<script>
function myFunction1()
{
var x;
var number1=prompt("Please Enter a Number", "");
var number2=prompt("Please Enter a Second Number", "");
var number3=prompt("Please Enter a Third Number", "");
var number4=prompt("Please Enter a Fourth Number", "");
document.getElementById("demo").innerHTML= Math.max (number1, number2, number3, number4);
}
</script>
</body>

当我在网络浏览器上将代码作为 html 文件运行时,该代码可以工作,但是当我将文件转换为 .js 时,它在从 HTML 调用时不起作用。我在这里做错了吗?

援助将不胜感激。

4

4 回答 4

3

If you want to create a .js file, all of the code in that file must be javascript. You would want to create the function like so:

function myFunction1()
{
var x;
var number1=prompt("Please Enter a Number", "");
var number2=prompt("Please Enter a Second Number", "");
var number3=prompt("Please Enter a Third Number", "");
var number4=prompt("Please Enter a Fourth Number", "");
document.getElementById("demo").innerHTML= Math.max (number1, number2, number3, number4);
}

And then, you would include the script in your HTML document

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

And from here you will be able to use the function as if it were part of your HTML page.

于 2013-04-17T13:36:32.830 回答
1

This is my JS Code that i am trying to call on html

That's an HTML document. A .js file should contain only JS. It shouldn't even have <script> tags in it.

于 2013-04-17T13:37:16.207 回答
1

我在 Webmatrix 上运行时遇到了这个问题。所以我不得不像这样更改 .js 文件的路径:

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

O 和 .js 文件应该只包含 javascript 代码:

function myFunction1()
{
var x;
var number1=prompt("Please Enter a Number", "");
var number2=prompt("Please Enter a Second Number", "");
var number3=prompt("Please Enter a Third Number", "");
var number4=prompt("Please Enter a Fourth Number", "");
document.getElementById("demo").innerHTML= Math.max (number1, number2, number3, number4);
}
于 2013-04-17T13:39:21.310 回答
0

检查以下内容:

  1. 检查 HTML、JS 文件是否在同一目录中或指定正确的位置。
  2. JS 文件不需要任何 HTML 标头。
  3. 在 HTML 文档的头部包含您的 JS 文件。
  4. 从 JS 文件中删除脚本和其他标签。

(对于 JS 文件,您甚至不需要添加文件类型,只需 src 就足够了)。

于 2013-04-17T13:44:48.870 回答