javascript - 如何在 DOM 上显示嵌套数据?
问题描述
尝试从 API 获取数据并将其添加到 DOM
具体来说,一个包含对象的数组。
以下是 API 在控制台中返回的示例。
我正在使用 for 循环和 for...in 循环来访问对象中的数组
下面的代码
const getNews = document.getElementById('btn')
heyThere = () => {
axios.get('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=APIKEY')
.then(function (response) {
for (let i = 0; i <= response.data.articles.length; i++) {
for (key in response.data.articles[i]) {
ham.innerHTML = (response.data.articles)
}
}
console.log(response)
console.log(typeof response)
})
.catch(function (error) {
console.log(error);
})
}
getNews.addEventListener('click', heyThere)
上面的代码将以下内容打印到 DOM
访问完整文章列表(20 篇文章)并将它们打印到 DOM 的正确方法是什么?
解决方案
您需要访问response.data.articles[i]
要显示的特定属性,并为每个属性创建所需的 HTML。就像是:
const getNews = document.getElementById('btn')
heyThere = () => {
axios.get('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=APIKEY')
.then(function(response) {
let html = '';
response.data.articles.each(article => {
html += '<div class="article">';
html += `<div class="author">${article.author}</div>`;
html += `<div class="description">${article.description}</div>`;
html += '</div>';
});
ham.innerHTML = html;
console.log(response)
console.log(typeof response)
})
.catch(function(error) {
console.log(error);
})
}
getNews.addEventListener('click', heyThere)
推荐阅读
- python - 为什么我安装的beautifulsoup 无法导入?
- mysql - Docker compose 无法运行 symfony 数据库命令
- excel - 如何在excel中的3个斜杠后获取字符串
- amazon-web-services - terraform 导入 Fargate 集群
- sql - PostgreSQL 全文模糊搜索按等级排序
- html - div 不会随边距或内边距向上移动
- node.js - NodeJS:保证异步函数的顺序
- php - imagettftext,来自 RTL 的阿拉伯语写作
- node.js - 使用 Axios 递归检查 GitLab 上的作业状态
- python - 如何可视化我的 QtWidgets.QToolButton