我的 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 中获取数据并同时用不同的新闻填充所有其他卡片??
答案 0 :(得分:0)
您好,欢迎来到社区。p>
看来您还有很多工作要做。 好吧,您必须首先考虑这个问题:您必须遍历所有卡片和所有组件,这是您没有做的事情。
这意味着:
.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');
//some code to skip to another card
});
记住这一点
const title = document.querySelectorAll(".title"),
image = document.querySelector(".image"),
source = document.querySelector(".source"),
url = document.querySelector(".url");
所有这些都是检索元素数组,因为您有七个元素,对吗? 在您的代码中,您一直指向图像、标题来源和 url,但没有指示索引。如果是这样的话,你会不断更新第一个。
尝试这样做:
.then(function(data){
let x=0;
data.articles.forEach(article => {
title[x].innerHTML = article.title;
image[x].style.backgroundImage = article.image;
source[x].innerHTML = article.source.name;
url[x].setAttribute('href', article.url);
url[x].setAttribute('target', '_blank');
x++
});
不过,这不是一个完美的解决方案。
看看 this page 并仔细阅读。花一些时间去做——我做到了!如果你还是不明白,请告诉我!