我刚刚开始学习JavaScript,并且刚刚让我的第一个程序变成一个简单的数字游戏。为了让用户反馈猜测,我使用了console.log()
。它在我曾经学过JavaScript(http://www.codecademy.com/learn)的网站上工作,但是当我把它放在记事本中时,将它保存为.htm
文件并运行它,我得到提示并确认,但没有可见来自console.log
命令的反馈。
如何让console.log
命令起作用?
以下是代码:
<Script language="JavaScript">
confirm("Are you ready to play 'I CAN GUESS THAT'? A game where Player 2 tries to guess player 1 number?");
//find out names
var player1 = prompt("Player 1 what is your name?","Your name here");
var player2 = prompt("Player 2 what is your name?","Your name here");
//player 1 number
var place_holder = 0;
var p1 =place_holder;
while (p1 > 1000 || p1 == 0) {
p1 = prompt(player2 + "look away." + " " + player1 + " " + "what is your number?", "Your number from 1 to 1,000 here");
if (p1 != parseInt(p1)) {
p1 = 0;
console.log("Error: Invalled Number!" + " " +player1 + " " + "Please choose a number between 1 and 1,000");
}
else if(p1>1000) {
console.log("Error: Invalled Number!" + " " +player1 + " " + "Please choose a number between 1 and 1,000");
}
};
//set up used guess list
var listlow = [];
var listhigh = [];
var x = 0;
var p2 = place_holder;
//game
while (x < 11) {
//list used guesses
console.log("Your guess so far");
console.log("Your to low guesses:"+" " + listlow);
console.log("Your to high gusses:"+" " + listhigh);
//player 2 guess
var p2 = prompt("Player 2 what is your guess?");
//good guess
var test = p1/p2;
if (test === 1) {
console.log("Congrats" + " " + player2 +" "+ "You have guessed"+" " + " " + player1 +" "+ "number");
var x = 30;
//to low
}
else if (test > 1) {
console.log(player2 +" "+ "Sorry your guess is to low");
listlow.push(p2);
x=x+1;
//to high
}
else if (test <1) {
console.log(player2 +" "+ "Sorry your guess is to high");
listhigh.push(p2);
x=x+1;
//something went wrong
}
else {
console.log("Opps something went wrong");
}
};
if (x < 20) {
console.log("Sorry" + " " +player2+ " "+ "You are out of guesses." +" " + player1+ " " + "wins!");
}
console.log("Thanks for playing")
</SCRIPT>
答案 0 :(得分:1)
问题在于CodeAcademy在其编码工具中有一个内置控制台,当您在Code Academy环境中处理其代码时,会向您显示。这是专门为您在构建代码时提供的帮助。
在大多数(现代)浏览器中都可以使用控制台,但默认情况下它们通常是隐藏的,因为它们主要由开发人员使用,而不是由日常用户使用。因此,将消息写入控制台中的用户并不是与他们通信的有效方式。
您可以通过多种方式向用户提供反馈。 。 。一些想法包括:
<div>
,专门用于发送消息并使用消息更新div的内容<textarea>
,专门用于发送消息并使用消息更新字段的值alert(MESSAGE_VALUE);
在弹出窗口中显示您的消息您决定如何做到这一点取决于您希望用户拥有哪种体验。 。 。这完全取决于你。
答案 1 :(得分:0)
这是在您的信息页上显示信息的简单方法。
<p id = "output"></p>
// Overwrites content in the output tag
function printText(str) {
document.getElementById("output").innerHTML = str;
}
OR
// Adds more content to the output tag
function printText(str) {
document.getElementById("output").innerHTML += str + "<br />";
}
然后根据需要向用户显示内容printText("some text")
。
这只是一个起点,有很多方法可以向用户传达信息,但希望这应该是您正在寻找的事情的开始。
答案 2 :(得分:0)
控制台API仅用于调试目的,而不是用于向用户输出消息或其他信息。
如果要将消息输出到屏幕,我建议您使用document.write()而不是console.log()。
document.write会将消息直接打印到您的Web浏览器(即页面的HTML正文)。
您可以在此处找到有关document.write()函数的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Document/write