1 回答
TA贡献1780条经验 获得超5个赞
尝试这个 :
在您的 html 中,您需要为动态神奇宝贝名称添加一个输入字段。
<input type="text" id="pokemon">
<button onclick="selectPokemonName()">Submit</button>
在您的脚本中添加以下代码:
function selectPokemonName() {
var pokemonName = document.getElementById("pokemon").value;
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: pokemonName,
}
const {url, type, id} = apiData
const apiUrl = `${url}${type}/${id}`
fetch(apiUrl)
.then( (data) => {
if(data.ok){
return data.json()
}
throw new Error('Response not ok.');
})
.then( pokemon => generateHtml(pokemon))
.catch( error => console.error('Error:', error))
}
const generateHtml = (data) => {
console.log(data)
const html = `
<div class="name">${data.name}</div>
<img src=${data.sprites.front_default}>
<div class="details">
<span>Height: ${data.height}</span>
<span>Weight: ${data.weight}</span>
</div>
`
const pokemonDiv = document.querySelector('.pokemon')
pokemonDiv.innerHTML = html
}
- 1 回答
- 0 关注
- 76 浏览
添加回答
举报