繁体   English   中英

如何让我的 JavaScript 读取 function 中的 HTML?

[英]How do I get my JavaScript to read the HTML within my function?

我正在制作一个 pokedex 来练习更多 JavaScript 并链接到 API,但我遇到了.innerHTML 的问题。 I am putting the HTML within the JavaScript function for the inner html to relay it to my site, but it is not registering with the JavaScript and says it is undefined.

这是代码:

document.querySelector("#search").addEventListener("click", getPokemon);
function getPokemon (e) {
   const name = document.querySelector(".pokemonName").value;
   const image = document.querySelector(".pokemonBox").value;
   console.log(name);
 fetch(`https://pokeapi.co/api/v2/pokemon/${name}`)
    .then(response => response.json())
    .then((data) => {
        
   
   
   image.innerHTML = `
   <div class="image-container"> <img class="image" src="${data.sprites.other["official- 
    artwork"].front_default}" alt="pokemon"/> 
   </div>
   <div class="name-container"> <p class="name"> Name: ${data.name} </p> <p></p></div>
   ` ;
   
   document.querySelector('.type').innerHTML = data.types.map(type => type.type.name);
}).catch((err) => {
    console.log('pokemon not found', err);
});
e.preventDefault();
}

是未定义的 image.innerHTML 吗? 需要查看 html 才能确定,但​​猜测const image = document.querySelector(".pokemonBox").value; 是要插入 innerHTML 的某种容器,您不希望 '.value' 因为这可能不存在。

您还需要返回承诺,或使用更新的语法,例如:

//I broke the function down to improve readability and separate concerns as you may wish to use the fetchPokemon call elsewhere in your app in the future so this would allow code reuse
const fetchPokemon = async (name) {
   let name = name;
   const pokemonData = await fetch(`https://pokeapi.co/api/v2/pokemon/${name}`)
   const pokemonJson = await pokemonData.json();
   console.log(pokemonJson);
   return pokemonJson;
}
const setImageInner = async (e) => {
   const name = document.querySelector(".pokemonName").value;
   const image = document.querySelector(".pokemonBox");
   console.log(name);
   const jsonData = await fetchPokemon(name)
   // you can now use jsonData directly
   image.innerHTML = `<div class="image-container"><img class="image" src="${jsonData.sprites.other.official-artwork.front_default}" alt="pokemon"/></div>`
  //etc... you get the idea

请注意您在哪里使用了<img class="image" src="${data.sprites.other["official-artwork"].front_default}" alt="pokemon"/>根据 api 文档...精灵。另一个是带有 3 个键的 object(注意 {}),因此您可以通过<img class="image" src="${data.sprites.other.official-artwork.front_default}" alt="pokemon"/>

还有你有 Name: ${data.name} 你的意思是使用你的 const 标记名称( const name = document.querySelector(".pokemonName").value;或来自 api 的名称,我问是因为看着API 在端点https://pokeapi.co/api/v2/pokemon/${name}没有名称键,而是在物种 ZA8CFDE6331BBD59EB2AC96F8911C4B666666上面我给出的例子。

这将是因为您没有将加号放在“image.innerHTML”中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM