我有一个简单的JavaScript代码,但它不起作用。我的代码是:
<html>
<head>
<title>JavaScript</title>
<script>
var target;
var guess_input;
var guesses = 0;
var finished = false;
var colors = ["black","blue","green","purple","red","white","yellow"];
function do(){
var random = Math.random();
var index = Math.floor(random * 7);
target = colors[index];
while(!finished){
guess_input = prompt("I am thinking of a color : black, blue, green, purple, red, white \n\n" + "What color am i thinking of?");
guesses++;
finished = check();
}
var myBody = document.getElementsByTagName("body")[0];
myBody.style.background = target;
}
function check(){
if (guess_input > target){
alert("your color is alphabetically higher than mine");
return false;
}
if (guess_input < target){
alert("your color is alphabetically lower than mine");
return false;
}
if (guess_input == target){
alert("your color is correct! it tooks you" + guesses "guesses to finish the game!");
return true;
}
else {
alert("Sorry, I do not recoginize your color");
return false;
}
</script>
</head>
<body onload = "do()">
</body>
</html>
错误消息是:Uncaught SyntaxError:意外的令牌 part2.html:53 Uncaught SyntaxError:Unexpected token),这是“function do()”,那么问题是什么?谢谢!
答案 0 :(得分:0)
您缺少用于功能检查的紧密括号,并将功能名称更改为其他功能,例如doSomething
<html>
<head>
<title>JavaScript</title>
<script>
var target;
var guess_input;
var guesses = 0;
var finished = false;
var colors = ["black","blue","green","purple","red","white","yellow"];
function doSomething(){
var random = Math.random();
var index = Math.floor(random * 7);
target = colors[index];
while(!finished){
guess_input = prompt("I am thinking of a color : black, blue, green, purple, red, white \n\n" + "What color am i thinking of?");
guesses++;
finished = check();
}
var myBody = document.getElementsByTagName("body")[0];
myBody.style.background = target;
}
function check(){
if (guess_input > target){
alert("your color is alphabetically higher than mine");
return false;
}
if (guess_input < target){
alert("your color is alphabetically lower than mine");
return false;
}
if (guess_input == target){
alert("your color is correct! it tooks you" + guesses "guesses to finish the game!");
return true;
}
else {
alert("Sorry, I do not recoginize your color");
return false;
}
}
</script>
</head>
<body onload="doSomething()">
</body>
</html>