javascript - 查找输入值并将其与 JSON 数据进行比较
问题描述
我正在尝试将用户输入值与 JSON 数据进行比较。
我发现了一些与此类似的问题,但它并没有解决我的问题。
这是我的代码,你知道为什么它不起作用吗?
Javascript
fetch('js/countries.json')
.then(res => res.json())
.then(data => {
function checkCountry() {
let input = document.getElementById("countryInput").value;
let country = data.find(check => check.country === "Norway");
let text;
if (input === data[country]) {
text = "Yes";
} else {
text = "No";
}
document.getElementById("alert").innerHTML = text;
}
document.getElementById("check").addEventListener("click", checkCountry);
console.log(data);
})
JSON
[{"country":"USA","active":true},
{"country":"Spain","active":true},
{"country":"Norway","active":true}]
HTML
<form action="">
<div class="input-container">
<input id="countryInput" type="text" placeholder="Country">
<i class="fas fa-search"></i>
</div>
<button id="check" type="button">CHECK</button>
</form>
解决方案
这条线不好:if (input === data[country]) {
您必须使用与上述国家/地区相同的机制进行检查...
let inputCountry = data.find(check => check.country === input);
像这样:
const data = [{"country":"USA","active":true},
{"country":"Spain","active":true},
{"country":"Norway","active":true}];
document.getElementById("check").addEventListener("click", checkCountry);
function checkCountry() {
let input = document.getElementById("countryInput").value;
let country = data.find(check => check.country === "Norway");
let inputCountry = data.find(check => check.country === input);
let text;
// You have to check with the country
if (inputCountry && input === inputCountry.country) {
text = "Yes";
} else {
text = "No";
}
console.log(text);
}
<form action="">
<div class="input-container">
<input id="countryInput" type="text" placeholder="Country">
<i class="fas fa-search"></i>
</div>
<button id="check" type="button">CHECK</button>
</form>
推荐阅读
- parsing - 无法为非 LR 语法找到 first() 和 follow()
- c# - 如何从 Azure Web App 本地存储中删除文件?
- geometry - 圆圈进度默认为 85,但输出显示 0
- python-3.x - 当我的代码需要提示输入并提供正确或不正确的百分比时,它返回一个空白值
- c# - TIFF 如何有序地放置图像
- python - 使用谷歌模块地图时的语法错误
- java - 无法在 Java Swing 中应用组合而不是继承
- python - 在共享云端硬盘中上传文件
- java - 为什么 Java Kafka Consumer 返回空记录列表?
- powershell - 如何仅将 Office 组的所有者添加到 SharePoint 组?