我已经为用户创建了一个邮政编码查询。当他们输入他们的邮政编码时,如果他们的邮政编码在列表中,那么它会报告他们在我们的服务区域之一。如果他们的邮政编码不在列表中,那么它将报告他们所在地区不提供服务。
我使用的示例代码运行良好,但我面临的挑战是我只使用了 3 个邮政编码,但我需要我的列表包含 100 个邮政编码。理想情况下,我希望引用一个包含这些邮政编码列表的外部文件,但如果没有,我可以在脚本中列出它们。我愿意接受建议。我目前正在使用开关。执行此操作的最佳方法是什么?
提前谢谢你。
这是我的代码:
<html>
<head>
<script>
function myFunction() {
var zipcode = document.getElementById("myZipCode").value;
var message;
switch(zipcode) {
case "85142":
case "99999":
case "88888":
message = "Service is available for your location.";
break;
default:
message = "Sorry your location is not available for service.<br />Click here to be notified once your location becomes available.";
}
document.getElementById("response").innerHTML = message;
}
</script>
</head>
<body>
<p>Enter your 5-digit Zip Code:</p>
<input id="myZipCode" type="text" maxlength="5">
<button onclick="myFunction()">Lookup</button>
<br />
<p id="response"></p>
</body>
</html>
我的代码也可在以下位置获得:https://jsfiddle.net/aplanet/7ttb19h5/11/
最佳答案
您的目标是支持哪种浏览器?如果你需要支持 IE9(Set
需要 IE11,而 .includes
根本无法在 IE 上运行),使用 indexOf
会很好用:
window.coveredZips = ['77777', '88888', '99999'];
document.addEventListener("DOMContentLoaded", function() {
var lookupButton = document.querySelector(".lookup-zip");
var response = document.getElementById("response");
var checkZipcodes = function() {
var zipcode = document.getElementById("myZipCode").value;
var message;
if (window.coveredZips.indexOf(zipcode) > -1) {
message = "Service is available for your location.";
} else {
message =
"Sorry your location is not available for service.<br />Click here to be notified once your location becomes available.";
}
response.innerHTML = message;
};
lookupButton.addEventListener("click", function() {
checkZipcodes();
});
});
<html>
<head>
</head>
<body>
<p>Enter your 5-digit Zip Code:</p>
<input id="myZipCode" type="text" maxlength="5">
<button class="lookup-zip">Lookup</button>
<br />
<p id="response"></p>
<script src="coveredZips.js"></script>
<script src="index.js"></script>
</body>
</html>
如果您查看 REPL: https://repl.it/@ryanpcmcquen/CheerfulWelllitDeveloper
您可以看到邮政编码可以存在于它们自己的文件中。
关于javascript - 创建一个 JavaScript 查找,将用户输入与大量项目列表进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49325258/