【发布时间】:2023-04-10 23:43:01
【问题描述】:
如果用户在这些条件下输入了正确答案,我必须检查(提示窗口是强制性的):
- 如果用户输入了正确答案,则提示“您是正确的”。
- 如果用户输入错误答案或将其留空,则提示“您错了” 3 如果用户按下取消按钮,则没有任何反应。
var num1 = Math.floor(Math.random() * 9 + 1);
var num2 = Math.floor(Math.random() * 9 + 1);
var result = num1 * num2;
var userInput = parseInt(prompt('What is ' + num1 + ' * ' + num2 + ' ?'));
if (userInput === result){
alert('You are correct!');
} else if (userInput === '' || userInput !== result) {
alert('You are wrong!');
} else if (userInput === null) {
alert('Cancelled!');
}
即使我按下取消,警报也会显示“你错了”。我添加了取消警报仅作为示例。有什么建议吗?
【问题讨论】:
-
虽然
prompt()确实在用户单击取消时返回null,但此信息在通过parseInt()时会丢失。在尝试解析结果之前,您应该检查null响应。
标签: javascript prompt