javascript - 找到邮政编码时验证邮政编码和打印状态
问题描述
此应用程序的主要目标是提供邮政编码搜索,然后在找到邮政编码后显示与邮政编码相关联的状态。如何修改此代码以反映我想要实现的目标?
<input type="text" id="zipCode" placeholder="ZIP code" onKeyUp="validateZip()"/>
<div id="msg"></div>
function checkIfAvailable(zip)
{
let zones = [["90210","Beverly Hills"],
["90211","BH"]]
return( zones.indexOf(zip) >= 0 )
}
function validateZip()
{
let zip = document.getElementById("zipCode").value;
let msg =""
if(checkIfAvailable(zip)
{
msg="Our service is available in" + State
;
}
else
{
msg="Sorry our service is not available in this area";
}
document.getElementById("msg").innerHTML = msg;
}
解决方案
如果您可以将其更改array
为 an object
,那么它将非常简单:
let zones = {90210: "Beverly Hills", 90211:"BH"};
let msgElement = document.getElementById("msg")
function validateZip(userInput) {
if (userInput.value in zones) {
msgElement.innerHTML = "Our service is available in " + zones[userInput.value];
} else {
msgElement.innerHTML = "Sorry our service is not available in this area";
}
}
<input type="text" id="zipCode" placeholder="ZIP code" onKeyUp="validateZip(this)"/>
<div id="msg"></div>
推荐阅读
- swift - 如何为全局调用创建一个枚举预期的硬编码字符串
- c# - 我找不到为什么我的不记名令牌无效,它返回 401
- python-3.x - 如何使用spacy中的短语匹配器将字符串的引理与列表的引理匹配
- amazon-web-services - 向强调标签添加参数时,控制台返回 SSML 错误
- python-3.x - 如何使用班级计算学生的字母等级
- java - 我无法弄清楚二叉树插入方法中的逻辑问题
- python - 对情节在线/离线/袖扣和不同版本感到困惑
- python - 将列作为列表导入到列标题变量
- android - 将 Android Gradle 插件更新到 3.2.0 或更高版本/生成 Flutter 签名的 APK
- apache - 通过 vhost 或 htaccess 创建子域