问题描述
我需要为数组 N1 的每个元素设置不同的 style.background 从数组 N2 中获取样式,forEach()
方法无法正常工作,因为它为每个元素返回相似的值。此外,我尝试将 i++ 用于 All_imagesExtended arr,但它只是将最终项目作为样式值。我不知道该怎么办。
let all_imagesExtanded = new Array(
"url(portfolio/inLake.jpg)","url(portfolio/train.jpg)","url(portfolio/tree.jpg)","url(assets/portfolio/window_and_girl.jpg)",)
let example = Array.from(document.querySelectorAll('.example_content'))
console.log(example)
example.forEach(function(elem){
elem.style.backgroundImage= all_imagesExtanded
})
解决方法
.forEach
回调函数的第二个参数是索引,您可以使用它来引用第一个数组中的 url。只需确保两个数组的长度相同即可。
example.forEach(function(elem,index){
elem.style.backgroundImage = all_imagesExtanded[index]
})
如果您确定 example
和 all_imagesExtanded
具有相同的长度,并且您想按索引分配值,则可以在 index
中使用 forEach
参数:>
example.forEach(function(elem,index){
elem.style.backgroundImage = all_imagesExtanded[index]
})
,
尝试这样的事情。
无需将 querySelectorAll 转换为 Array。
通过索引访问数组中的样式。 (all_imagesExtanded[i]
)
const N2 = ["red","green"];
document.querySelectorAll('.box').forEach((ele,i) => {
ele.style.color = N2[i];
});
<div class="box"> one </div>
<div class="box"> two </div>