繁体   English   中英

HTML,JavaScript和ERR_FILE_NOT_FOUND错误

[英]HTML, JavaScript and ERR_FILE_NOT_FOUND error

我有一个带有javascript代码的简单html页面。

HTML

<!doctype html>
<html>
   <head>
      <meta charset="utf-8" />
      <title>Sink The Battle Ship</title>
   </head>
   <body>
      <h1>Battleship</h1>
      <script src="battleship.js"></script>
   </body>
</html>

JavaScript的

var location = Math.floor(Math.random() * 5);
var numberOfGuesses = 0;
var isSunk = false;
var guess;
var guess = prompt("Ready, aim, fire! (enter a number from 0-6):");
var guessedLocation = parseInt(guess);
console.log(guess);
console.log(guessedLocation);

每次我在浏览器中启动html时,都会显示提示,当我输入一个值时,它会给出一个错误“ERR_FILE_NOT_FOUND”。 看起来浏览器正在尝试使用我输入的值重定向到页面。 知道这里出了什么问题吗? 我尝试在不同的浏览器中打开html但仍然没有运气。

问题是您正在重新定义一个名为location的全局变量。

当你声明一个这样的变量时

var location = 1;

这样做是一样的

window.location = 1;

位置是一个浏览器变量,用于定义用户所在的页面(位置)。

你可以做两件事,

1 - 将您的变量位置重命名为:$ location,location_2,my_location

var myLocation = Math.floor(Math.random() * 5);

2 - 创建本地范围

(function(){
    var location = Math.floor(Math.random() * 5);
    var numberOfGuesses = 0;
    var isSunk = false;
    var guess = prompt("Ready, aim, fire! (enter a number from 0-6):");
    var guessedLocation = parseInt(guess);
    console.log(guess);
    console.log(guessedLocation);
})()

另外,停止重新声明变量guess,只对每个变量名使用ONE'var'

 (function(){ var location = Math.floor(Math.random() * 5); var numberOfGuesses = 0; var isSunk = false; var guess; var guess = prompt("Ready, aim, fire! (enter a number from 0-6):"); var guessedLocation = parseInt(guess); console.log(location); console.log(guessedLocation); guessedLocation == location ? console.log('you sank me!') : console.log('ha! missed...') })(); 
 <!doctype html> <html> <head> <meta charset="utf-8" /> <title>Sink The Battle Ship</title> </head> <body> <h1>Battleship</h1> <script src="battleship.js"></script> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM