因此,我试图随机生成一个口袋妖怪,然后再生成五个相同类型的口袋妖怪,以显示在网页上。到目前为止,这就是我所拥有的:
const pokemonName = document.querySelector(".pokemon-name");
const pokemonImage = document.querySelector(".pokemon-image");
function getPokemon() {
const pokemonArr = []
const random = Math.floor(Math.random() * 256 + 1)
axios.get("https://pokeapi.co/api/v2/pokemon/1" + random)
.then(function (response) {
pokemonName.innerHTML = response.data.forms[0].name;
pokemonImage.src = response.data.sprites.front_default;
pokemonArr.push(pokemonName.innerHTML)
})
.catch(function (error) {
pokemonName.innerHTML = "An error has occurred.";
pokemonImage.src = "";
});
}我已经成功地显示了一个口袋妖怪,尽管它仍然很精致。我的思维过程是将名称和图像附加到数组或对象中,但我在试图应用该逻辑时遇到了问题。这是我第一次介绍API和使用Axios的概念。我能用循环吗?我如何比较API中Pokemon的类型?
口袋妖怪API:https://pokeapi.co/
发布于 2022-02-26 04:32:13
https://replit.com/@heyitsmarcus/PokemonContainer#index.html
上面是下面代码说明的演示。
如果您想在页面上填充X数量的口袋妖怪,那么使用类是正确的。但是,您需要利用querySelectorAll功能来利用类。这将允许您在类上运行一个for循环,并为每个匹配的选择器选择不同的口袋妖怪。例如,您确实希望有一个pokemon-container类,它分别存放pokemon-name和pokemon-image类,如下所示:
<div class="pokemon-container">
<div class="pokemon-name"></div>
<img class="pokemon-image" src="">
</div>
<div class="pokemon-container">
<div class="pokemon-name"></div>
<img class="pokemon-image" src="">
</div>
<div class="pokemon-container">
<div class="pokemon-name"></div>
<img class="pokemon-image" src="">
</div>对您想要看到的口袋妖怪数量重复此操作。然后,您可以在3个for类上运行一个pokemon-container循环,以查看3个随机的口袋妖怪,同时仍然使用与以前相同的名称。不同的是,您只需要运行一个querySelector来获取该容器的特定的单独的口袋妖怪名称和图像。这将导致每次3个随机的口袋妖怪!=]
function getNewPokemon() {
//this loop grabs every pokemon container individually
const pokemonContainers = document.querySelectorAll('.pokemon-container');
for (const container of pokemonContainers) {
//Grab this specific container's pokemon name element
const pokemonName = container.querySelector('.pokemon-name');
//Grab this specific container's pokemon image element
const pokemonImage = container.querySelector('.pokemon-image');
//Get your random integer
const random = Math.floor(Math.random() * 256 + 1);
//also I removed the 1 from after the final slash because you're excluding pokemon by including that 1 in the URL
//and you can just use the natural JavaScript "fetch"
//there's really no need for a whole library for a request like this
axios.get(`https://pokeapi.co/api/v2/pokemon/${random}`)
.then(json => {
pokemonName.innerHTML = json.data.forms[0].name;
pokemonImage.src = json.data.sprites.front_default;
})
.catch(error => {
console.error('error in request', error);
pokemonName.innerHTML = "An error has occurred.";
pokemonImage.src = "";
})
}
}https://stackoverflow.com/questions/71273927
复制相似问题