簡體   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