我是一个新手自学如何通过udemy.com使用课程编写代码。我正在学习Javascript,作为一个项目,我们被指示创建一个简单的Javascript游戏。基本上你输入一个你认为计算机正在思考的数字。到目前为止,当您输入正确的数字并单击提交时,将出现一个框,表明"耶!这就是我举起的手指的数量!"或者如果它不正确,它将说明"抱歉这不正确,我的号码是......"
问题是我无法弄清楚如何添加额外的if语句。例如,我试图提醒一条消息,说明你需要输入一个数字" o;当用户单击提交按钮而不在框中输入数字或字母时。当他们猜到0的正确数字时,警告信息将显示"那是对的,我没有手指!"
以下是允许我正确执行上面列出的两条指令的代码:
<p>How many fingers am I holding up?</p>
<input id="answer"/>
<button id="myButton"><strong>Submit</strong></button>
<script type="text/javascript">
document.getElementById("myButton").onclick=function() {
var x=Math.random();
x=6*x;
x=Math.floor(x); //use floor to get whole number
if (x==document.getElementById("answer").value) {
alert("Yay! That's exactly how many fingers I'm holding up!");
} else {
alert("Sorry that's not correct! My number was" + x );
}
}
</script>
我在这里做错了什么?
提前致谢!
答案 0 :(得分:0)
var x = Math.random();
x = 6*x;
x = Math.floor(x); //use floor to get whole number
var y = document.getElementById("answer").value;
if(y == null){
alert("Please enter a number");
}else{
if (x == y) {
if(x == 0){
alert("Yay! I'm not holding any fingers up!");
}else{
alert("Yay! That's exactly how many fingers I'm holding up!");
}
} else {
alert("Sorry that's not correct! My number was" + x );
}
}
答案 1 :(得分:0)
这是一个修改过的脚本,问题在于.value属性。请修改你的缩进。
请点击此链接查看完整代码JS fiddle
document.getElementById("myButton").onclick = function() {
var x = Math.random();
var y = document.getElementById("answer");
x = 6 * x;
x = Math.floor(x); //use floor to get whole number
if (y.value === "") {
alert("Oops, you need to enter a number!");
} else if (x == y.value) {
if (x == 0) {
alert("That's right, I have no fingers up!");
} else {
alert("Yay! That's exactly how many fingers I'm holding up!");
}
} else {
alert("Sorry that's not correct! My number was " + x);
}
}