*"; ar.forEach(function(x){ var -6ren">
gpt4 book ai didi

javascript - 为什么 div 里面的 div 颜色不会通过 JavaScript 数组改变

转载 作者:太空宇宙 更新时间:2023-11-04 16:12:26 24 4
gpt4 key购买 nike

    var ar = ['.two_in','.three_in','.four_in'], pb =  "> *";
ar.forEach(function(x){
var sel = document.querySelectorAll( x + pb);

var colors = {};
colors[ar[0]] = 'blue';
colors[ar[1]] = 'green';
colors[ar[2]] = 'red';

for(var i = 0;i<sel.length;i++){
sel[i].style.backgroundColor = colors[sel[i].className];
}
})
<div class="two_in">
<div class="demo">blue</div>
<div class="demo">blue</div>
<div class="demo">blue</div>
</div>
<br>
<div class="three_in">
<div class="demo">green</div>
<div class="demo">green</div>
<div class="demo">green</div>
</div>
<br>

<div class="four_in">
<div class="demo">red</div>
<div class="demo">red</div>
<div class="demo">red</div>
</div>

我想将 two_in 内的所有 div 颜色分别更改为蓝色、third_in 为绿色、four_in 为红色,缺少的代码是什么?谁能解释一下吗?

示例:

two_in 内的所有 div(div 类为 demo 的三个 div)应为蓝色,至于 two_infour_in

最佳答案

错误如下:

colors[ar[0]] = 'blue';
colors[ar[1]] = 'green';
colors[ar[2]] = 'red';

它在那里分配一个非原始索引。您需要的是:

var ar = ['.two_in', '.three_in', '.four_in'],
pb = " > *";
ar.forEach(function(x) {
var sel = document.querySelectorAll(x + pb);
var colors = {};
colors[0] = 'blue';
colors[1] = 'green';
colors[2] = 'red';

for (var i = 0; i < sel.length; i++) {
sel[i].style.backgroundColor = colors[i];
}
})
<div class="two_in">
<div class="demo">blue</div>
<div class="demo">blue</div>
<div class="demo">blue</div>
</div>
<br>
<div class="three_in">
<div class="demo">green</div>
<div class="demo">green</div>
<div class="demo">green</div>
</div>
<br>
<div class="four_in">
<div class="demo">red</div>
<div class="demo">red</div>
<div class="demo">red</div>
</div>

以上是你想要的吗?或者,如果您需要基于文本的颜色,那么...

var ar = ['.two_in', '.three_in', '.four_in'],
pb = " > *";
ar.forEach(function(x) {
var sel = document.querySelectorAll(x + pb);
var colors = {};
colors['blue'] = 'blue';
colors['green'] = 'green';
colors['red'] = 'red';

for (var i = 0; i < sel.length; i++) {
sel[i].style.backgroundColor = colors[sel[i].innerHTML.trim()];
}
})
<div class="two_in">
<div class="demo">blue</div>
<div class="demo">blue</div>
<div class="demo">blue</div>
</div>
<br>
<div class="three_in">
<div class="demo">green</div>
<div class="demo">green</div>
<div class="demo">green</div>
</div>
<br>
<div class="four_in">
<div class="demo">red</div>
<div class="demo">red</div>
<div class="demo">red</div>
</div>

关于javascript - 为什么 div 里面的 div 颜色不会通过 JavaScript 数组改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41355418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com