简体   繁体   English

HTML,JavaScript和ERR_FILE_NOT_FOUND错误

[英]HTML, JavaScript and ERR_FILE_NOT_FOUND error

I have a simple html page with javascript code. 我有一个带有javascript代码的简单html页面。

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 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);

Every time I launch the html in browser, the prompt displays and when I enter a value, it gives me an error "ERR_FILE_NOT_FOUND". 每次我在浏览器中启动html时,都会显示提示,当我输入一个值时,它会给出一个错误“ERR_FILE_NOT_FOUND”。 It looks like the browser is trying to re-direct to a page with the value I entered. 看起来浏览器正在尝试使用我输入的值重定向到页面。 Any idea what is going wrong here? 知道这里出了什么问题吗? I tried opening the html in different browsers and still no luck. 我尝试在不同的浏览器中打开html但仍然没有运气。

The problem is that you are redefining a global variable, called location. 问题是您正在重新定义一个名为location的全局变量。

When you declare a variable like this 当你声明一个这样的变量时

var location = 1;

is the same as doing this 这样做是一样的

window.location = 1;

Location is a browser variable used to define in which page (location) the user is in. 位置是一个浏览器变量,用于定义用户所在的页面(位置)。

You can do two things, 你可以做两件事,

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

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

2 - Create a local scope 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);
})()

Also, stop re-declaring the variable guess, only use ONE 'var' for every variable name 另外,停止重新声明变量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