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

如何通过<input>选择角色后展示API中的对应数据?

解决哈利波特角色信息页面展示问题

我在练习中使用API:https://raw.githubusercontent.com/Laboratoria/LIM011-data-lovers/master/src/data/potter/potter.json,已经写好包含<input>、<datalist>和触发按钮的HTML结构,想要实现输入或选择角色名后点击按钮,展示该角色的对应信息,但当前JS代码只能在控制台打印角色名,无法把信息显示到页面的character区域,求解决方法。

现有代码

HTML代码

<body>
    <h1>Person of the day</h1>
    <h2>Choose a character</h2>
    <div class="form">
        <label for="choose">Choose</label> <br>
        <input list="list-people" type="text" name="choose" class="form-control" id="input" placeholder="Write here"/>
        <datalist id="list-people">
            <option value="Harry Potter">
            <option value="Hermione Granger">
            <option value="Ron Weasley">
            <option value="Draco Malfoy">
            <option value="Minerva McGonagall">
        </datalist>
        <button id="myBtn">Try it</button>
    </div>
    <section id="character"></section>
</body>

JavaScript代码

const characterDom = document.getElementById('character');

let url = "https://raw.githubusercontent.com/Laboratoria/LIM011-data-lovers/master/src/data/potter/potter.json";

const fetchAll = url => {
  fetch(url)
    .then((res) => res.json())
    .then(data => {
      const result = data;
      console.log(result)
      document.getElementById("myBtn").addEventListener("click", displayName);

      function displayName() {
        document.getElementById("input").innerHTML = `$(actor.name[0])`;
        for (let actor of result) {

          console.log(actor.name);
          if (actor.name == document.getElementById("input").value) {

          }
        }
      }
    })
    .catch((error) => {
      console.error(error);
    });
}

fetchAll(url)

问题分析与修复方案

原代码核心问题是找到匹配角色后未做页面渲染,同时存在语法错误和无效操作。以下是修复后的完整JS代码:

const characterDom = document.getElementById('character');
const inputEl = document.getElementById('input');
const btnEl = document.getElementById('myBtn');

let url = "https://raw.githubusercontent.com/Laboratoria/LIM011-data-lovers/master/src/data/potter/potter.json";

const fetchAll = url => {
  fetch(url)
    .then((res) => res.json())
    .then(data => {
      btnEl.addEventListener("click", () => displayCharacter(data));
    })
    .catch((error) => {
      console.error(error);
      characterDom.innerHTML = '<p>加载数据失败,请稍后重试</p>';
    });
}

function displayCharacter(characters) {
  const inputValue = inputEl.value.trim();
  const matchedChar = characters.find(actor => actor.name === inputValue);
  
  if (matchedChar) {
    characterDom.innerHTML = `
      <div class="character-card">
        <h3>${matchedChar.name}</h3>
        <p><strong>性别:</strong>${matchedChar.gender}</p>
        <p><strong>学院:</strong>${matchedChar.house || '无'}</p>
        <p><strong>出生日期:</strong>${matchedChar.dateOfBirth || '未知'}</p>
        <p><strong>饰演演员:</strong>${matchedChar.actor}</p>
      </div>
    `;
  } else {
    characterDom.innerHTML = `<p>未找到名为${inputValue}的角色</p>`;
  }
}

fetchAll(url)

关键修改点

  • 移除原代码中修改input元素innerHTML的无效操作,改为获取输入框的值
  • 用Array.find()替代循环,更高效匹配目标角色
  • 添加页面渲染逻辑:找到匹配角色后,通过模板字符串构建信息卡片插入到character区域;未找到时给出提示
  • 将按钮点击监听移到循环外,避免重复绑定事件
  • 增加请求失败时的页面错误提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 11:39:46