You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript Fetch调用Pokemon API:数据已获取但无法渲染到页面元素

解决Pokemon API数据无法渲染到页面的问题

问题根源分析

  1. 元素选择方式错误:document.getElementsByClassName()返回的是HTMLCollection元素集合,不是单个DOM元素,直接对集合设置src或innerHTML不会生效,需通过索引[0]获取单个元素,或改用document.querySelector()直接定位单个元素。
  2. Class名称拼写不一致:HTML中背向图片的class是back-pick,但JS代码里写成了back-pic,导致无法匹配到目标元素。
  3. 冗余无效操作:fetch()外层包裹的console.log()只会打印Promise对象,毫无意义;String(data.sprites.front_default)属于冗余转换,API返回的该字段本身就是字符串类型。

修复后的代码

script.js

"use strict";

document.querySelector(".button").addEventListener("click", () => {
  fetch("https://pokeapi.co/api/v2/pokemon/ditto")
    .then((res) => res.json())
    .then((data) => {
      const weight = data.weight;
      const frontPic = data.sprites.front_default;
      const backPic = data.sprites.back_default;
      const name = data.name;
      console.log(weight, frontPic, backPic, name);

      // 直接定位单个元素并赋值
      document.querySelector(".front-pic").src = frontPic;
      document.querySelector(".back-pick").src = backPic;
      document.querySelector(".pokemon-weight").textContent = weight;
    })
    .catch(err => console.error('请求出错:', err)); // 新增错误捕获,方便调试
});

Index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link href="style.css" rel="stylesheet" />
    <title>Pokemon Searcher</title>
  </head>
  <body>
    <header>
      <h1>POKEMON SEARCHER</h1>
    </header>

    <div class="search">
      <label for="pokemon">Enter the pokemon name</label>
      <input type="text" id="pokemon" placeholder="Pikachu" />
      <button class="button">SEARCH</button>
    </div>

    <img class="front-pic" alt="Pokemon front view" />
    <img class="back-pick" alt="Pokemon back view" />
    <p class="pokemon-weight"></p>
  </body>
  <script src="script.js"></script>
</html>

额外优化建议

  • 给图片添加alt属性,提升页面可访问性;
  • 使用textContent替代innerHTML设置纯文本内容,避免XSS风险;
  • 可扩展功能:读取输入框内容动态请求对应宝可梦数据,替换固定的ditto,示例代码:
    const pokemonName = document.getElementById('pokemon').value.trim();
    fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`)
    

内容的提问来源于stack exchange,提问作者Abijith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 20:52:44