将路径数组中的 html 集合 (img) 的 src 属性设置为使用 ES6 纯 Javascript 在每个 img



我有一个src值数组,如[path1, path2, path3]和一个与arr值相同的数组长度的html集合。所以我想传递每个值来设置 html 元素的 src。我该怎么办?我尝试了 for Each,for Of,映射,但它仍然是同一路径中的所有元素,或者只设置了一个(第一个元素(。

//My code now
<img alt='first-in-collection'>
<img alt='second-in-collection'>
<img alt='third-in-collection'> 
//The variable
let arr = ['path1', 'path2', 'path3']
//Expected result 
<img src='path1' alt='first-in-collection'>
<img src='path2' alt='second-in-collection'>
<img src='path3' alt='third-in-collection'>

我的运行代码链接

不需要在图像和路径数组上运行循环。在任何一个阵列上运行循环。继续增加迭代器计数并设置当前迭代器索引图像的 src。

let arr = ['path1', 'path2', 'path3'];
// get all images
let img = document.getElementsByClassName('img-thumbnail')
// initialize iterator with 0    
let i=0;     
for(let el of arr){
// set attribute of corresponding image
img[i++].setAttribute('src', el)

}
<div class="col-8">
<div class="row produit-desc-lense">
<div class="col-4 text-center border-bottom">
<img class="img-fluid rounded img-thumbnail" alt="/">
<h5>caméra 2</h5>
</div>
<div class="col-4 d-flex align-items-center justify-content-center border-bottom">
<p></p>
</div>
<div class="col-4 d-flex align-items-center justify-content-center border-bottom">
<select id="selectNumber">
<option>Choose a number</option>
</select>
</div>
</div><div class="row produit-desc-lense">
<div class="col-4 text-center border-bottom">
<img class="img-fluid rounded img-thumbnail" alt="/">
<h5>caméra 2</h5>
</div>
<div class="col-4 d-flex align-items-center justify-content-center border-bottom">
<p></p>
</div>
<div class="col-4 d-flex align-items-center justify-content-center border-bottom">
<select id="selectNumber">
<option>Choose a number</option>
</select>
</div>
</div><div class="row produit-desc-lense">
<div class="col-4 text-center border-bottom">
<img class="img-fluid rounded img-thumbnail" alt="/">
<h5>caméra 2</h5>
</div>
<div class="col-4 d-flex align-items-center justify-content-center border-bottom">
<p></p>
</div>
<div class="col-4 d-flex align-items-center justify-content-center border-bottom">
<select id="selectNumber">
<option>Choose a number</option>
</select>
</div>
</div>

</div>

最新更新