【发布时间】:2020-01-06 14:07:27
【问题描述】:
我觉得我在这里遗漏了一些非常基本的东西......总结是我有一组 10 张卡片,对应于我网站上的 10 个不同的集合。每张卡片都有一个图像元素。我想用一张新卡替换那张卡,其中图像的来源和其他一些项目已经改变(而且我还添加了动画)。
问题是我从另一个站点 (website/collectionName/configs.ini) 获取的新图像源的获取仅适用于循环中的最后一张卡。
let cardsOnly = document.createElement("div");
cardArray = document.querySelectorAll('.cards');
cardArray.forEach(function(card) {
//do a bunch of stuff to the card like add title and remove old classes
card.appendChild(cardTitleDiv);
collectionName = //grabbed from this page
bgImage = document.createElement("img");
let configWebsite = website/collectionName/configs.ini
const request = async () => {
const response = await fetch(configWebsite)
const text = await response.text() //so now I have the text from the config website
newImgSource = //extracted from text
console.log(collectionName + " " + newImgSource);
bgImage.setAttribute("src", newImgSource);
console.log(bgImage);
card.appendChild(bgImage);
}
request();
//do a bunch of other stuff to the card like add description div
card.appendChild(descriptionDiv);
cardsOnly.appendChild(card); //add all cards to cardsOnly div
}
//append the cardsOnly div to my wrapper on the page.
当页面加载时,卡片都有正确的标题、正确的描述,这是奇怪的部分……第一个 console.log,对于数组中的 10 个卡片中的每一个,它都输出了正确的 collectionName以及我刚刚提取并提取的正确的新图像源....
但当我查看cardsOnly div 时,唯一带有<img> 元素的卡片是最后一张卡片。并且在 request()... 中的 console.log(bgImage) 一直输出与最后(第 10 个)卡片相对应的 <img> 元素。
我的控制台如下所示:
collection1: correct new image source for collection 1
<img> element for collection 10 with correct img src for collection 10
collection2: correct new img src for collection 2
<img> element for collection 10 with correct img src for collection 10
etc..
etc..
为什么会这样?
【问题讨论】:
-
request是异步的,但您从不等待它。请咨询this。
标签: javascript html fetch