2017-02-19 27 views
4

我有一個簡單的HTML頁面與JavaScript代碼。HTML,JavaScript和ERR_FILE_NOT_FOUND錯誤

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,但仍然沒有運氣。

+1

沒有幫助。 –

+0

請檢查我的答案,我剛纔在這裏評論說,在我5年的js開發中,這是我第一次看到這個錯誤,哈哈哈,我不知道這可能發生,但它確實有道理。 –

回答

3

問題是你正在重新定義一個叫做位置的全局變量。

當你聲明這樣

var location = 1; 

一個變量是一樣的做這個

window.location = 1; 

位置是用來定義在頁面(位置)的用戶是在瀏覽器中的變量。

你可以做兩件事,

1 - 重命名你的變量位置:$位置,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); 
})() 

此外,停止重新聲明變量的猜測,只能使用一個 '無功' 爲每個變量名

(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>

+1

非常感謝。解決了我的問題。我剛剛開始使用JavaScript,並開始討論它。 –

+0

沒問題,只要記住將最佳答案標記爲答案,以便我們可以獲得甜蜜的聲望點 –