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

时间:2016-12-28 04:36:53

标签: javascript selectors-api

    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_infour_in

1 个答案:

答案 0 :(得分:1)

这是错误:

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

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

&#13;
&#13;
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;
&#13;
&#13;

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

&#13;
&#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;
&#13;
&#13;