簡體   English   中英

根據數組列表更改 div 背景顏色

[英]Change div background color according to list of array

如何將數組中找到的背景顏色應用於 class 名稱矩形的每個 div。

<div id="rectangleWrapper">

<div id="rectangle-1">

</div>
<div id="rectangle-2">

</div>
</div>

const rectWrapDiv = document.getElementById("rectangleWrapper").children;
for (const prop of rectWrapDiv){
prop.classList.add("rectangle");
}

const bcgColor = ["red", "blue" ];
for (let i = 0; i < rectWrapDiv.length; i++){

for (let j = 0; j < bcgColor.length; j++){
    rectWrapDiv[i].style.background  = bcgColor[j];
console.log(bcgColor[j])
}

}

當我在控制台瀏覽器中顯示它時,只有索引 1 被用作所有 div 的背景。

只需使用一次for子級和 bcgColor 長度相同的數組。

 const rectWrapDiv = document.getElementById("rectangleWrapper").children; for (const prop of rectWrapDiv) { prop.classList.add("rectangle"); } const bcgColor = ["red", "blue"]; for (let i = 0; i < rectWrapDiv.length; i++) { rectWrapDiv[i].style.background = bcgColor[i]; }
 #rectangle-1, #rectangle-2 { height: 50px; }
 <div id="rectangleWrapper"> <div id="rectangle-1"> </div> <div id="rectangle-2"> </div> </div>

您在 i 的每次迭代中重新初始化 j,所以如果我們遍歷您的代碼:

i=0
j=0
recWrapDiv[0].style.background = bcgcolor[0]; 
now j=1
recWarpDiv[0].style.background = bcgcolor[1];
now i=1 and j will loop through 0 and 1 again
now j=0 again
recWrapDiv[1].style.background = bcgcolor[0]; 
now j=1
recWrapDiv[1].style.background = bcgcolor[1];
Finished
//All elements are set to bcgcolor[1].

我會改變你的 for j 循環來實現你想要的。

你可以使用 querySelectorAll

 const bcgColor = ["red", "blue" ]; document.querySelectorAll("#rectangleWrapper div").forEach((div, i) => { div.style.backgroundColor = bcgColor[i]; });
 #rectangleWrapper div { height: 50px; margin: 4px; }
 <div id="rectangleWrapper"> <div id="rectangle-1"> </div> <div id="rectangle-2"> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM