簡體   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