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

JavaScript构建Pokédex时innerHTML报undefined问题求助

宝可梦图鉴innerHTML报错问题解决

核心错误原因

你代码里的const image = document.querySelector(".pokemonBox").value;是关键问题:.pokemonBox是用来渲染宝可梦信息的DOM容器(比如<div>),并非表单输入控件,不需要读取.value属性。这会导致image变量拿到undefined,自然无法调用.innerHTML。

修复步骤

  1. 修正容器元素获取
    将获取容器的代码改为直接获取DOM元素:

    const image = document.querySelector(".pokemonBox");
    
  2. 优化类型渲染体验
    当前类型渲染会直接输出逗号分隔的字符串,建议改成带样式的标签形式,提升可读性:

    document.querySelector('.type').innerHTML = data.types.map(type => `<span class="type-item">${type.type.name}</span>`).join(' ');
    
  3. 添加边界处理(可选)

    • 输入空值时提示用户,避免无效API请求
    • 添加加载状态,让用户知道请求正在进行
    • 处理API返回的错误状态(比如404)

修正后的完整代码

document.querySelector("#search").addEventListener("click", getPokemon);
function getPokemon (e) {
   const name = document.querySelector(".pokemonName").value.trim();
   const imageContainer = document.querySelector(".pokemonBox");
   const typeContainer = document.querySelector('.type');

   // 空值判断
   if (!name) {
       imageContainer.innerHTML = "<p>请输入宝可梦名称</p>";
       typeContainer.innerHTML = "";
       return;
   }

   // 显示加载状态
   imageContainer.innerHTML = "<p>加载中...</p>";
   typeContainer.innerHTML = "";

   fetch(`https://pokeapi.co/api/v2/pokemon/${name.toLowerCase()}`)
    .then(response => {
        if (!response.ok) throw new Error("未找到该宝可梦");
        return response.json();
    })
    .then((data) => {
       imageContainer.innerHTML = `
       <div class="image-container"> 
           <img class="image" src="${data.sprites.other["official-artwork"].front_default}" alt="${data.name}"/> 
       </div>
       <div class="name-container"> 
           <p class="name"> 名称: ${data.name} </p> 
       </div>
       ` ;
       
       typeContainer.innerHTML = data.types.map(type => `<span class="type-tag">${type.type.name}</span>`).join(' ');
   }).catch((err) => {
       imageContainer.innerHTML = `<p>${err.message}</p>`;
       console.log('请求错误', err);
   });
   e.preventDefault();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:48:23