【问题标题】:setAttribute with a loop带循环的 setAttribute
【发布时间】:2021-02-15 10:23:02
【问题描述】:

我正在尝试使用循环为多个图像设置 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"
  }
]

你知道错误是什么吗? 谢谢。

【问题讨论】:

  • document.querySelectorAll('.image') 返回一个元素列表。你可能应该按索引来做。
  • 查看数据示例会非常有帮助

标签: javascript html for-loop setattribute


【解决方案1】:

试试这个

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

【讨论】:

  • 我已经放好了我的数组。很抱歉之前没有这样做。因此,您的代码不起作用,因为我没有与您放入 const 数据的数组相同的数组。你认为我应该改变我的数组还是有其他方法可以处理我的数组样式?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    相关资源
    最近更新 更多