【发布时间】:2020-04-06 14:37:11
【问题描述】:
在学校,我正在使用 Pokemon API,我正在努力让人们可以输入 Pokemon 名称,它会向他们显示那个 pokemon,而不是我为他们选择的 pokemon。
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="style.css">
<title> Pokemon </title>
</head>
<body>
<script src="script2.js"></script>
<h1>PokeDex</h1>
<div id="poke_container" class="poke-container"></div>
<div class="pokemon">
</div>
</body>
</html>
我现在得到的js代码是这样的:
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: 'ditto',
}
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
}
这将显示一个 Ditto,但我希望它使人们可以输入某些内容并显示该口袋妖怪。
【问题讨论】:
-
那么问题出在哪里?出了什么问题?是否报告错误?有任何事情发生吗?
-
只需使用输入框中的值更新
id。 -
您所问的内容有点复杂-您需要:1. 将输入字段添加到屏幕,2. 捕获您希望处理其中的值的时间,通常是旁边的按钮.处理按钮单击 - 从输入中获取 id 值。 -- 接下来你需要重组你的 JS - 需要以受控的方式调用 fetch。 1. 页面加载时 - 您可能希望获取 Ditto 作为默认值。 2 当单击按钮搜索其他 pokemon 时,获取 text/id 并传递给您的新 fetch 函数并在您的 fetch URL 中使用它。
-
@developer ye 这就是我正在尝试的,但我无法让它工作。你能帮我解决一下代码吗?
标签: javascript html json api