【发布时间】:2021-05-10 13:59:35
【问题描述】:
我的 html 中有 7 张卡片,包括图片、标题、描述和来源列。我正在尝试从 gnews api 获取数据,然后用从 api 获得的数据填充我的卡片。我想要来自 api 的数据来交换我的占位符文本和图像。但我只能在我的 HTML 中交换第一张卡片中的详细信息。
API 中的 JSON 如下所示:
"articles": [
{
"title": "xxx xxx",
"description": "xxx xxx xxx",
"content": "xxx xxx xxx xxx... [1514 chars]",
"url": "xxx xxx",
"image": "xxx.jpg",
"publishedAt": "xxx",
"source": {
"name": "xxx",
"url": "xxx.com/"
}
}
]
我尝试了一个 forEach,但它只得到了第一张卡片
const title = document.querySelectorAll(".title"),
image = document.querySelector(".image"),
source = document.querySelector(".source"),
url = document.querySelector(".url");
.........
.then(function(data){
data.articles.forEach(article => {
title.innerHTML = article.title;
image.style.backgroundImage = article.image;
source.innerHTML = article.source.name;
url.setAttribute('href', article.url);
url.setAttribute('target', '_blank');
});
}
// And also i tried to target every card individually which worked but that means i would have
// to target all 7 html cards that i have which would be quite cumbersome and repetitive to write.
// Below is the code for the individual targetting..
news.title = data.articles[0].title;
news.image = data.articles[0].image;
news.source = data.articles[0].source.name;
news.url = data.articles[0].url;
news.description = data.articles[0].description;
我如何编写代码以便能够从所有文章 JSON 中获取数据并同时用不同的新闻填充所有其他卡片??
【问题讨论】:
标签: javascript html arrays api dom