gpt4 book ai didi

javascript - 查找输入值并将其与 JSON 数据进行比较

转载 作者:行者123 更新时间:2023-11-28 14:08:08 27 4
gpt4 key购买 nike

我正在尝试将用户输入值与 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>

关于javascript - 查找输入值并将其与 JSON 数据进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60533689/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com