我正在尝试根据预先确定的邮政编码列表检查用户输入。我使用document.getElementById("zipcode").value创建了一个表示用户输入的变量,并设置了要检查的邮政编码数组。这曾经有效过一次,但我想我在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");
}
}
} 发布于 2017-08-27 05:28:01
代码中的问题是,您只存储了一次输入值,这是在代码第一次运行的时候,并且第一次运行时的值为空"" (如果您没有在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> }https://stackoverflow.com/questions/45899763
复制相似问题