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颜色分别更改为蓝色,将three_in
更改为绿色,将four_in
分别更改为红色,缺少的代码是什么?谁能解释一下呢?
示例:
two_in
内的所有div(div类为demo
的三个div)应为蓝色,three_in
和four_in
。
答案 0 :(得分:1)
这是错误:
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];
}
})
&#13;
<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>
&#13;
以上是你想要的吗?或者,如果您需要基于文本的颜色,那么......
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()];
}
})
&#13;
<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>
&#13;