简体   繁体   English

如何使用 JavaScript 以编程方式更改图像的 SRC 值

[英]How Do I Programmatically Change The SRC value of the images using JavaScript

The images do not have unique ids nor do they have unique classes .这些图像没有唯一的ids ,也没有唯一的classes How do I change the src value for each element from the array of images.如何更改图像数组中每个元素的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'];

The second argument of forEach is the index of the current iterated item. forEach的第二个参数是当前迭代项的索引。

Grab the image elements with querySelectorAll , and then use forEach to iterate over them updating the src attribute of each image with the element at the appropriate index in the array.使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM