如何使对象属性的值可从输入标签中搜索

我有这个我正在使用的api,我想让国家(即value.slug == china)成为用户的搜索项,因为我在代码中手动输入它们以获得每个国家的结果。


我希望能够将 api 与我的 html 表单输入标签连接起来,以便用户自己搜索国家/地区。


这是代码


fetch('https://api.covid19api.com/summary')

        .then(function (response) {

            return response.json();

        })

        .then(function (data) {

            let country = data.Countries.filter((value) => value.Slug == 'china')

            appendData(country);


        })

        .catch(function (err) {

            console.log(err);

        });


泛舟湖上清波郎朗
浏览 79回答 1
1回答

慕斯709654

使用纯 javascript,您可以执行以下操作:var input = document.querySelector("#input")input.addEventListener("change", function(event) { // enter key triggers event&nbsp; &nbsp;var value = event.target.value;&nbsp; &nbsp;console.log(value);&nbsp; &nbsp;getData(value);});function appendData(data) {&nbsp; // stub&nbsp; console.log(data);}function getData(country) {fetch('https://api.covid19api.com/summary')&nbsp; &nbsp; &nbsp; &nbsp; .then(function (response) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return response.json();&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .then(function (data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let country = data.Countries.filter((value) => value.Slug == country)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; appendData(country);&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .catch(function (err) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(err);&nbsp; &nbsp; &nbsp; &nbsp; });}<input type="text" id="input" />
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript