【问题标题】:How to display nested data on the DOM?如何在 DOM 上显示嵌套数据?
【发布时间】:2018-08-24 22:10:49
【问题描述】:
尝试从 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 的正确方法是什么?
【问题讨论】:
标签:
javascript
arrays
json
for-loop
axios
【解决方案1】:
您需要访问要显示的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)
【解决方案2】:
下面的解决方案将文章作为列表打印到 DOM。
heyThere = () => {
axios.get('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=APIKEY')
.then(function (response) {
let news = response.data.articles
for (let i = 0, len = news.length; i < len; i++) {
console.log(news[i])
let li = document.createElement('li')
li.innerHTML = JSON.stringify(news[i].title)
document.querySelector('#ham').appendChild(li)
}
})
.catch(function (error) {
console.log(error);
})
}
getNews.addEventListener('click', heyThere)
下面是打印到页面的文章
使用点符号更改响应允许返回 URL、作者等列表。例如,li.innerHTML = JSON.stringify(news[i].url)
希望这有帮助!