如何使用上次进行的API调用来填充html字段



我正在学习rest API和async/await,所以我只是在用pokeapi做一个小项目。

我在";输入";调用API,然后填充html字段。

问题是当一个id被插入时;123〃;这将产生三个请求,fetchPokemon("1"(、fetchPokermon("12"(和fetchPoker mon("123"(,就目前而言,这不是问题。但它有时所做的是;12〃;饰面在第三个请求"之后;123〃;因此最后填充的html字段是来自";12〃;要求

有没有一种简单的方法可以让它总是填写最后一个请求?

const pokemonId = document.getElementById("pokemon-id");
const pokemonName = document.getElementById("pokemon-name");
const pokemonType = document.getElementById("pokemon-type");
const pokemonHeight = document.getElementById("height");
const pokemonWeight = document.getElementById("weight");
const pokemonSearch = document.getElementById("pokemon-search");
async function fetchPokemon(idOrName) {
const endpoint = "https://pokeapi.co/api/v2/pokemon/";
const response = await fetch(endpoint + idOrName);
if (!response.ok) return null;
return response.json();
}
function fillPokemonFields(pokemon) {
if(!pokemon) return;
pokemonId.textContent = pokemon.id;
pokemonName.textContent = pokemon.name;
pokemonType.textContent = pokemon.type;
pokemonHeight.textContent = pokemon.height;
pokemonWeight.textContent = pokemon.weight;
}
pokemonSearch.addEventListener("input", async function () {
let input = this.value;
let pokemon;
// TODO validation
pokemon = await fetchPokemon(input);
fillPokemonFields(pokemon);
});

html

<main>
<input type="text" id="pokemon-search">

<div id="pokemon-id"></div>
<div id="pokemon-name"></div>
<div id="pokemon-type"></div>
<div id="pokemon-height"></div>
<div id="pokemon-weight"></div>
</main>

问题出在.addEventListener部分

input事件与change事件几乎相同,这意味着每当用户输入密钥时,它都会更新。这就是为什么使用1、12和123进行3次调用的原因

溶液

在表单上使用submit而不是input

yourFormElement.addEventListener("submit", function (e) {
// this is needed to avoid default functionality of the onsubmit method
e.preventDefault();
// do stuff here...
});

最新更新