Javascript 带有循环的setAttribute

Javascript 带有循环的setAttribute,javascript,html,for-loop,setattribute,Javascript,Html,For Loop,Setattribute,我试图通过循环将src属性设置为多个图像。我有8张图片,我想把这8张图片插入我的html。我在一个来自JSON文件的数组上使用for of循环。我的JSON似乎还可以,因为我可以console.log属性源的良好值。这些值如下所示:“images/img1.png”。img1变为img2。。。 问题是它将images/img8.png添加到控制台中的所有图像中,而在html中只添加一个图像 我试图放置querySelectorAll('.image'),但它显示TypeError:img.set

我试图通过循环将src属性设置为多个图像。我有8张图片,我想把这8张图片插入我的html。我在一个来自JSON文件的数组上使用for of循环。我的JSON似乎还可以,因为我可以console.log属性源的良好值。这些值如下所示:“images/img1.png”。img1变为img2。。。 问题是它将images/img8.png添加到控制台中的所有图像中,而在html中只添加一个图像

我试图放置querySelectorAll('.image'),但它显示
TypeError:img.setAttribute不是函数

我试图在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"
  }
]
你知道错误是什么吗?
谢谢。

querySelectorAll
返回类似数组的列表。您可能需要将该列表与图像列表一起迭代

.then(response => response.json())
.then(data => {
  let img = document.querySelectorAll('.image') 
  for (var i =0;i<data.length;i++) {
    img[i].setAttribute('src', item[i].source)
  }
}).catch(err => console.error("Une erreur est survenue", err))
.then(response=>response.json())
。然后(数据=>{
让img=document.queryselectoral('.image'))
对于(var i=0;i console.error(“Une erreur est survenue”,err))
试试这个

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))

如果图像的id与图像的id匹配,则可以使用该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))

document.querySelectorAll('.image'))
返回元素列表。您可能应该按索引执行。查看我放入数组的数据示例会非常有帮助。很抱歉以前没有执行此操作。因此,您的代码不起作用,因为我没有与放入常量数据的数组相同的数组。您认为我应该使用数组还是有其他方法处理我的数组数组的le?@Luckyluchie请参见更新的示例