我有一个带有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但仍然没有运气。
答案 0 :(得分:3)
问题在于您正在重新定义一个名为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&#39; var&#39;对于每个变量名称
(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...')
})();
&#13;
<!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>
&#13;