我有一个输入字段,它只能在1和4之间取数字。如果数字介于1和4之间,它会运行一些代码。如果没有,它会发出一个警告,告诉用户再次尝试1到4之间的数字。这是我的代码
var number = document.getElementById("num").value;
if(Number(number) === 1 || Number(number) === 2 || Number(number) === 3 || Number(number) === 4 ){
//success code here///
}
else if(Number(number) !== 1 || Number(number) !== 2 || Number(number) !== 3 || Number(number) !== 4) {
} alert("Please type a whole number between(and including) 1 and 4 into the input field.");
我了解到'.value;'函数返回一个字符串,即使该值是一个数字。所以我把var'数字'放在Number()中;将其转换为数字的函数。 问题是,当我在输入字段中输入1时。即使它等于1,它也会发出警报。其他任何数字都不起作用。我检查了控制台,没有语法错误(也根据DreamWeaver)。帮助将非常感谢:)
答案 0 :(得分:1)
我认为您犯了一个简单的错误,即将警报置于else if
条款之外。
但是,您可以采取一些其他措施来使其更具可读性和效率。
// Call Number() here so you only have to do it once
var number = Number(document.getElementById("num").value);
// You can also do something like parseInt(document.getElementById("num").value)
// Now check to see if Number() or parseInt() actually parsed an integer out of their input
// and then check that if it's outside your number range
if (isNaN(number) || number < 1 || number > 4) {
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
} else {
// Do Successful code
}
答案 1 :(得分:0)
我们也可以这样写
var patt1 = /[1-4]/g;
if(patt1.test(number)){
//success code here///
}
else{
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
}