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

使用Pokemon API时搜索过滤器功能异常,寻求技术帮助

宝可梦信息展示页面搜索过滤器功能异常求助

我基于Pokemon API开发了宝可梦信息展示页面,已成功获取API数据并完成页面布局,但搜索过滤器功能无法正常工作,排查多日未找到问题所在,以下是相关代码,恳请大家提供技术帮助,谢谢!


原始代码

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="dist/css/styles.css">
    <title>Pokemon API</title>
</head>
<body>
        <main>
            <header>
                <nav>
                    <div class="navContainer">
                        <div class="logo">
                            <img src="imgs/pokemon-logo-png (1).png" alt="">
                        </div>
                        <div class="navLinks">
                        <ul class="menu">
                            <li class="list"><a>Home</a></li>
                            <li class="list"><a>Archive</a></li>
                            <li class="list"><a>Pokemon</a></li>
                            <li class="list"><a>About</a></li>
                        </ul>
                        </div>
                    </div>
                </nav>
            </header>
            <div class="search">
                <input type="text" class="search-bar" name="search" placeholder="search pokemon">
            </div>
            <div class="allPokemonContainer">

            </div>
        </main>
        <script src="app.js"></script>
</body>
</html>

CSS

body {
  margin: 0;
  padding: 0;
}

.pokeContainer {
  border: 2px solid black;
  margin: 1rem;
  background-color: rgb(255, 255, 255);
}

.flex-container {
  display: flex;
  text-align: center;
  justify-content: space-around;
}

img {
  width: 100%;
}

h3 {
  text-align: center;
}

p {
  width: 50px;
  border: 1px solid black;
  border-radius: 11px;
  text-align: center;
  background-color: rgb(95, 158, 160);
  color: rgb(255, 255, 255);
}

ul {
  padding: 0.5rem;
  text-transform: uppercase;
}

ul.menu {
  display: flex;
  text-align: center;
}

li.list {
  color: black;
}

li {
  width: 100px;
  border-radius: 5px;
  padding: 0.1rem;
  list-style: none;
  margin: 0.5rem;
  font-size: 10px;
  font-weight: 600;
}

.search {
  display: flex;
  justify-content: center;
}

JavaScript

function getHTML() {
    fetch('https://pokeapi.co/api/v2/pokemon?limit=151')
        .then((data) => data.json())
    .then((allPokemon) => {
        allPokemon.results.forEach(function(pokemon) {
            getPokeData(pokemon)
        })
    })
}

function getPokeData(pokemon) {
    const url = pokemon.url;
    fetch(url)
    .then((data) => data.json())
    .then(function(pokemon) {
        createPokeCard(pokemon)
    })
}

 function createPokeCard(pokemon) {
    const allPokemonContainer = document.querySelector('.allPokemonContainer');
    const pokeContainer = document.createElement('div');
    pokeContainer.classList.add('pokeContainer');

    let pokeName = pokemon.name;
    let pokeId = pokemon.id;
    let pokeTypes = pokemon.types[0].type.name;
    let pokeAbilities = pokemon.abilities[0].ability.name;

    const pokemonInnerHTML = `<div class="pokeContainer">
    <img srcset=${`https://nexus.traction.one/images/pokemon/pokemon/${pokeId}.png`}>
       <h3>${pokeName}</h3>
     <p>${pokeId}</p>
      <div class="flex-container">
      <div class="types">
       <h4>Types</h4>
       <ul>
        <li>pokeTypes}</li>
      <li>${pokeTypes}</li>
       </ul>
       </div>
      <div class="Abilities">
      <h4>Abilities</h4>
     <ul>
     <li>pokeAbilities}</li>
      </li>${pokeAbilities}</li>
      </ul>
      </div>
       </div>
     </div>`;

pokeContainer.innerHTML = pokemonInnerHTML;
allPokemonContainer.append(pokeContainer);

    searchFilter();
 }

const searchFilter = (data) => {
    const searchBar = document.querySelector('.search-bar');

    searchBar.addEventListener('keyup', (event) => {
        const pokeContainer = document.querySelectorAll('.pokeContainer');
        const value = event.target.value.toLowerCase();
        pokeContainer.forEach((container) => {
            if (searchBar.name.toLowerCase().includes(value)) {
                container.style.display = 'block'
            } else {
                container.style.display = 'none'
            }
        })
    })
}

问题分析与修复方案

核心错误点

  1. 搜索逻辑错误:searchFilter中用searchBar.name(输入框的name属性值"search")做匹配,而非宝可梦名称,完全偏离需求。
  2. 重复绑定事件:每次创建卡片都调用searchFilter(),导致搜索框重复绑定keyup事件,触发多次无效逻辑。
  3. HTML模板语法错误:模板中存在pokeTypes}、多余闭合标签等语法问题,导致页面渲染异常。
  4. 信息展示不全:仅提取第一个类型和能力,丢失宝可梦的多属性信息。

修复后的完整代码

JavaScript

function getHTML() {
    fetch('https://pokeapi.co/api/v2/pokemon?limit=151')
        .then((data) => data.json())
        .then((allPokemon) => {
            allPokemon.results.forEach(pokemon => getPokeData(pokemon))
        })
}

function getPokeData(pokemon) {
    fetch(pokemon.url)
        .then((data) => data.json())
        .then(pokemon => createPokeCard(pokemon))
}

function createPokeCard(pokemon) {
    const allPokemonContainer = document.querySelector('.allPokemonContainer');
    const pokeContainer = document.createElement('div');
    pokeContainer.classList.add('pokeContainer');

    const pokeName = pokemon.name;
    const pokeId = pokemon.id;
    // 提取所有类型和能力
    const pokeTypes = pokemon.types.map(item => item.type.name);
    const pokeAbilities = pokemon.abilities.map(item => item.ability.name);

    // 生成动态列表HTML
    const typesHTML = pokeTypes.map(type => `<li>${type}</li>`).join('');
    const abilitiesHTML = pokeAbilities.map(ability => `<li>${ability}</li>`).join('');

    const pokemonInnerHTML = `<div class="poke-card">
        <img src="https://nexus.traction.one/images/pokemon/pokemon/${pokeId}.png" alt="${pokeName}">
        <h3>${pokeName}</h3>
        <p>${pokeId}</p>
        <div class="flex-container">
            <div class="types">
                <h4>Types</h4>
                <ul>${typesHTML}</ul>
            </div>
            <div class="Abilities">
                <h4>Abilities</h4>
                <ul>${abilitiesHTML}</ul>
            </div>
        </div>
    </div>`;

    pokeContainer.innerHTML = pokemonInnerHTML;
    allPokemonContainer.append(pokeContainer);
}

// 页面加载完成后仅绑定一次搜索事件
document.addEventListener('DOMContentLoaded', () => {
    const searchBar = document.querySelector('.search-bar');

    searchBar.addEventListener('keyup', (event) => {
        const value = event.target.value.toLowerCase();
        document.querySelectorAll('.pokeContainer').forEach(container => {
            const cardName = container.querySelector('h3').textContent.toLowerCase();
            container.style.display = cardName.includes(value) ? 'block' : 'none';
        })
    });

    // 初始化加载数据
    getHTML();
});

优化后的CSS(可选)

添加网格布局让卡片排列更规整:

.allPokemonContainer {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1rem;
  padding: 1rem;
}

.pokeContainer {
  border: 2px solid black;
  margin: 0;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:41:48