为何JavaScript Fetch API的forEach循环仅返回最后一个数组对象?
解决每次点击按钮依次展示单篇文章的问题
你的核心问题是每次点击时用forEach循环覆盖innerHTML,导致最终只显示最后一篇文章,而且每次点击都重新请求API,无法实现依次切换文章的效果。以下是具体解决方案:
关键修改思路
- 缓存文章数据:把API返回的文章数组存到全局变量,避免每次点击重复请求
- 记录当前展示索引:用变量跟踪当前显示的文章位置,每次点击切换到下一篇
- 单篇渲染:不再用循环覆盖DOM,而是根据当前索引渲染对应文章
修改后的完整代码
JavaScript 代码
const searchBtn = document.getElementById('generate'); const result = document.getElementById('result'); // 全局变量:缓存文章数据、当前展示索引 let articles = []; let currentIndex = 0; searchBtn.addEventListener('click', function () { // 如果还没获取过文章数据,先请求API if (articles.length === 0) { const url = 'https://newsapi.org/v2/everything?' + 'q=Apple&' + 'from=2022-08-15&' + 'sortBy=popularity&' + 'apiKey=xxxxx'; fetch(url) .then((response) => response.json()) .then((data) => { articles = data.articles; // 渲染第一篇文章 renderArticle(currentIndex); }); } else { // 切换到下一篇,超出数组长度则重置到第一篇 currentIndex = (currentIndex + 1) % articles.length; renderArticle(currentIndex); } }); // 单独的文章渲染函数 function renderArticle(index) { const article = articles[index]; // 处理作者可能为null的情况,避免显示undefined const author = article.author || 'Unknown'; result.innerHTML = ` <div class="result-header"> <h1>${article.title}</h1> <p> <span>Author:</span> ${author}</p> <p>${article.source.name}</p> </div> <div class="result-content"> <p> Description: ${article.description || 'No description available'}</p> <p>${article.content || 'No content preview available'} <a href="${article.url}" target="_blank">Click here for full article</a></p> </div> `; }
修正的细节说明
- 修复了原代码中
class"result-header"和class"result-content"的语法错误,补充了等号= - 增加了对
author、description、content为空的处理,避免页面显示undefined - 给文章链接添加了
target="_blank",让文章在新标签页打开 - 用
(currentIndex + 1) % articles.length实现循环切换,展示完最后一篇后回到第一篇
CSS 和 HTML 代码(无需修改)
保留你原有的CSS和HTML代码即可。
内容的提问来源于stack exchange,提问作者Jonathan Alvarez
相关产品推荐
相关产品推荐

