我正在接收用户输入,我希望它验证该号码是否有效。如果它不在0-100之间,那么我想显示消息“无效”。现在,即使我输入2000,如果用户温暖或冷,它仍然会显示。我希望它停止执行并显示无效消息。
// Hot or Cold JS game.
$(document).ready(function() {
$('#number').on('keyup keypress', function(e) {
if (e.keyCode < 48 || e.keyCode > 57)
return false;
});
var randomNumber = Math.floor((Math.random() * 100 ) + 1);
$('#Enter').click(function() {
var guessNumber = document.getElementById('number').value;
if (guessNumber < 0 || guessNumber > 100) {
// Display invalid input
console.log('Not valid');
$('output-container').text('Enter a number between 0 and 100').css('color', 'silver');
};
var difference = Math.abs(guessNumber - randomNumber);
if (difference == 0) {
// Display to user - "Perfect"
$('.output-container').text('Perfect').css('color', 'green');
} else if (difference < 5) {
// Display to user - You're on Fire!
$('.output-container').text('You are on Fire!').css('color', 'red');
} else if (difference < 10) {
// Display to user - Warm
$('.output-container').text('Warm').css('color', 'orange');
} else if (difference < 30) {
// Display to user - Ice Cold
$('.output-container').text('Ice Cold').css('color', 'blue');
} else {
// Display to user - You must be Frozen?
$('.output-container').text('You must be Frozen!').css('color', 'royalblue');
};
});
// Start over
$('#reset').click(function() {
location.reload();
});
$('#show').click(function() {
$('#show').hide();
$('#append-number').append(randomNumber);
});
});
以下是它如何运行的示例。 http://jsfiddle.net/jonathanbello/32cuW/
答案 0 :(得分:2)
输出错误后,您只需添加return false
即可。
你错过了output-container
...
if (guessNumber < 0 || guessNumber > 100) {
// Display invalid input
console.log('Not valid');
$('.output-container').text('Enter a number between 0 and 100').css('color', 'silver');
return false;
};
...