我试图根据预定的邮政编码列表检查用户输入。我使用document.getElementById("zipcode").value
创建了一个表示用户输入的变量,并设置了我的zipcodes数组以进行检查。这工作一次,但我想我在if / else中包含了break;
。我错过了什么?
输入框转换为字符串,所以我也创建了数组元素字符串。我很困惑。
<h2>Zipcode checker</h2>
<input id="zipcode" name="address-4" type=text maxlength="5" value="" pattern="[0-9]" required/>`
<button id="btn" value="submit" type="submit" onclick="myStuff()">Register</button>
脚本:
var btnInput = document.getElementById("zipcode").value;
var acceptedZip = ["85392", "85340", "85393", "85353", "85341"];
function myStuff() {
for (var i = 0; i < acceptedZip.length; i++) {
if (acceptedZip[i] === btnInput) {
alert("we got you boo");
}
else {
alert("sorry son");
}
}
}
答案 0 :(得分:1)
您的代码中的问题是您只存储输入的值一次,这是第一次运行代码时,第一次运行时的值为空""
(如果你没有在html中设置它。
你可以用这个做你想做的事:
<h2>Zipcode checker</h2>
<input id="zipcode" name="address-4" type=text maxlength="5" value="" pattern="[0-9]" required/>`
<button id="btn" value="submit" type="submit" onclick="myStuff()">Register</button>
<script>
var btnInput = document.getElementById("zipcode"); // store the button outside
var acceptedZip = ["85392", "85340", "85393", "85353", "85341"];
function myStuff() {
var exists = acceptedZip.indexOf(btnInput.value)>-1 ; // get the value of the input inside (each time the button is pressed)
alert(exists ? "we got you boo" : "sorry son");
}
</script>
我正在使用JavaScript的三元运算符,基本上是:
<cond 1> ? <act 1> : <cond 2> ? <act 2> : <act 3>
equivalent to :
if (<cond 1>) { act 1 } else if (<cond 2>) { <act 2> } else { <act 3> }