尝试创建一个带有 ID 的对象

对于学校,我正在使用 Pokemon API,我试图让人们可以输入 Pokemon 名称,它会向他们显示该 Pokemon,而不是我为他们选择的 Pokemon。


html代码:


<!DOCTYPE html>

<html>

    <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

}

这将显示一个同上,但我希望人们可以输入一些东西,它会显示那个神奇宝贝。


芜湖不芜
浏览 41回答 1
1回答

翻阅古今

尝试这个 :在您的 html 中,您需要为动态神奇宝贝名称添加一个输入字段。<input type="text" id="pokemon"><button onclick="selectPokemonName()">Submit</button>在您的脚本中添加以下代码:function selectPokemonName() {&nbsp; var pokemonName = document.getElementById("pokemon").value;&nbsp; const apiData = {&nbsp; url: 'https://pokeapi.co/api/v2/',&nbsp; type: 'pokemon',&nbsp; id: pokemonName,&nbsp; }const {url, type, id} = apiDataconst apiUrl = `${url}${type}/${id}`fetch(apiUrl)&nbsp; &nbsp; .then( (data) => {&nbsp; &nbsp; &nbsp; &nbsp; if(data.ok){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return data.json()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; throw new Error('Response not ok.');&nbsp;&nbsp; &nbsp; })&nbsp; &nbsp; .then( pokemon => generateHtml(pokemon))&nbsp; &nbsp; .catch( error => console.error('Error:', error))}const generateHtml = (data) => {&nbsp; &nbsp; console.log(data)&nbsp; &nbsp; const html = `&nbsp; &nbsp; &nbsp; &nbsp; <div class="name">${data.name}</div>&nbsp; &nbsp; &nbsp; &nbsp; <img src=${data.sprites.front_default}>&nbsp; &nbsp; &nbsp; &nbsp; <div class="details">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>Height: ${data.height}</span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>Weight: ${data.weight}</span>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; `&nbsp; &nbsp; const pokemonDiv = document.querySelector('.pokemon')&nbsp; &nbsp; pokemonDiv.innerHTML = html}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5