如何解决带循环的 setAttribute
我正在尝试使用循环将 src 属性设置为多个图像。我有 8 张图片,我想将这 8 张图片插入到我的 html 中。我在来自 JSON 文件的数组上使用 for of 循环。我的 JSON 似乎没问题,因为我可以在 console.log 中记录属性源的良好值。值如下所示:“images/img1.png”。 img1 变成 img2 ... 问题是它把images/img8.png 放到了控制台中的所有图像中,而html 中只有一个图像。
我尝试放置 querySelectorAll('.image') 但它显示 TypeError: img.setAttribute is not a function
。
我试图将另一个循环放入 for of 循环中,但它构成了一个无限循环,仍然是 images/img8.png。
这是我的代码:
.then(response => response.json())
.then(data => {
let img = document.querySelectorAll('.image')
for (const item of data) {
img.setAttribute('src',item.source)
console.log(img)
}
}).catch(err => console.error("Une erreur est survenue",err))
这是我的数组
[
{
"image_name": "Image1","image_id": "1","source": "images/img1.png"
},{
"image_name": "Image2","image_id": "2","source": "images/img2.png"
},{
"image_name": "Image3","image_id": "3","source": "images/img3.png"
},{
"image_name": "Image4","image_id": "4","source": "images/img4.png"
},{
"image_name": "Image5","image_id": "5","source": "images/img5.png"
},{
"image_name": "Image6","image_id": "6","source": "images/img6.png"
},{
"image_name": "Image7","image_id": "7","source": "images/img7.png"
},{
"image_name": "Image8","image_id": "8","source": "images/img8.png"
}
]
你知道错误是什么吗? 谢谢。
解决方法
googl-service.json
返回一个类似数组的列表。您大概需要迭代该列表以及您的图像列表
querySelectorAll
,
试试这个
const images = document.querySelectorAll('.image'); // a collection
....
.then(response => response.json())
.then(data => data.forEach(({source,image_name},i) => {
images[i].src = source;
images[i].alt = image_name;
})
).catch(err => console.error("Une erreur est survenue",err))
https://jsfiddle.net/mplungjan/sehx2bc4/
如果图像的 ID 与 image_id 匹配,您可以使用它而不是集合和 [i]
.then(response => response.json())
.then(data => data.forEach(({source,image_name,image_id}) => {
const image = document.getElementById(image_id);
image.src = source;
image.alt = image_name;
})
).catch(err => console.error("Une erreur est survenue",err))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。