[英]How do I dynamically change the src attribute of a collection of images in JavaScript?
[英]How Do I Programmatically Change The SRC value of the images using JavaScript
这些图像没有唯一的ids
,也没有唯一的classes
。 如何更改图像数组中每个元素的src
值。
<img src="img1.jpg" />
<img src="img2.jpg" />
<img src="img3.jpg" />
<img src="img4.jpg" />
var images = ['img11.jpg', 'img22.jpg','img33.jpg','img44.jpg'];
forEach
的第二个参数是当前迭代项的索引。
使用querySelectorAll
获取图像元素,然后使用forEach
迭代它们,使用数组中适当索引处的元素更新每个图像的src
属性。
const arr = ['img11.jpg', 'img22.jpg','img33.jpg','img44.jpg']; const images = document.querySelectorAll('img'); images.forEach((image, index) => image.src = arr[index]);
<img src="img1.jpg" /> <img src="img2.jpg" /> <img src="img3.jpg" /> <img src="img4.jpg" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.