点击按钮仅提取JSON中卢克·天行者的姓名身高输出到HTML的解决方案
代码修改方案
核心修改逻辑
你现有代码遍历了接口返回的所有角色数据,所以会输出全部内容,只需要新增筛选条件匹配Luke Skywalker即可,同时修复原代码中渲染容器选择错误的问题。
第一步:修改HTML代码(新增结果渲染容器)
<article class="product"> <div class="img-container"> <img src="img/r5-d4.jpg" alt="luke-skywalker" class="product-img" /> <button class="bag-btn" id="getInfo">Info</button> </div> <!-- 新增专门用来放角色信息的容器 --> <div id="charResult"></div> </article>
第二步:修改JS代码
有两种可选实现方案:
方案1:在现有全量请求基础上筛选(适合需要同时处理多角色的场景)
// 选中触发查询的按钮和结果渲染容器 const getInfoBtn = document.getElementById('getInfo'); const resultContainer = document.getElementById('charResult'); getInfoBtn.addEventListener('click', () => { fetch("https://swapi.dev/api/people") .then((res) => res.json()) .then((data) => { // 筛选姓名为Luke Skywalker的角色 const targetChar = data.results.find(char => char.name === 'Luke Skywalker'); // 组装输出内容 const output = ` <div> <h3>${targetChar.name}</h3> <h4>身高:${targetChar.height}cm</h4> </div> `; // 渲染内容到页面 resultContainer.innerHTML = output; // 控制台仅输出目标角色信息 console.log(targetChar.name, targetChar.height); }); });
方案2:直接请求Luke的专属接口(性能更优,数据传输量更小)
因为星战API中Luke Skywalker的固定资源地址为https://swapi.dev/api/people/1/,可以直接请求该接口,不需要拉取全量角色列表:
const getInfoBtn = document.getElementById('getInfo'); const resultContainer = document.getElementById('charResult'); getInfoBtn.addEventListener('click', () => { // 直接请求Luke的个人数据接口 fetch("https://swapi.dev/api/people/1/") .then((res) => res.json()) .then((targetChar) => { const output = ` <div> <h3>${targetChar.name}</h3> <h4>身高:${targetChar.height}cm</h4> </div> `; resultContainer.innerHTML = output; console.log(targetChar.name, targetChar.height); }); });
原代码问题说明
- 你用
getElementsByTagName获取到的是所有按钮的集合,不能直接给整个集合赋值innerHTML,需要指定单个元素或者专门的渲染容器 - 原逻辑用
forEach遍历了所有角色数据,所以会输出全部内容,改用find方法匹配目标姓名即可只获取需要的信息
内容的提问来源于stack exchange,提问作者David Momoh
相关产品推荐
相关产品推荐

