2016-12-26 32 views
-3

类的名字通过数组在javascript

var ar = ["blue", "green", "red"], 
 
    x = document.getElementsByTagName('DIV'), 
 
    i, 
 
    colors = {}; 
 

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

 
for (i = 0 ; i < x.length ; i++) { 
 
    x[i].style.backgroundColor = colors[x[i].className]; 
 
}
.one_in,.two_in ,three_in{ width:100px; height:100px; border:1px solid #000; }
<div class="blue one_in"> 
 
</div><div class="green two_in"> 
 
</div><div class="one_in"> 
 
</div><div class="red "></div>

为什么不工作,当我把多个类和空间,如果我把空白的阵列["blue" + " ", "green" + " ", "red"+ " "],does not工作如何实现这一目标?

当我从div删除班,这会再次工作?

+1

第一件事,缺少*' 。*在'.one_in,.two_in,three_in'中的'three_in'前面 –

回答

1

为了达到预期的效果,请使用以下选项

x[i].style.background = colors[x[i].className.split(' ')[0]]; 

http://codepen.io/nagasai/pen/rWgPRj

+0

谢谢@Naga,但你能解释这 – Anjali

+0

@Anjali:我甚至在这个答案之前添加了相同的答案和得到downvoted:D –

+0

我分裂的类名字符串与空格(''),并获得第一类名 - className.split('')[0] –

0

你找错了值...

x[i].style.backgroundColor = colors[x[i].className];

类名是“红色”,“绿色two_in”和“蓝one_in”

您需要完全匹配的类名。

与jQuery不同,classNames对于你来说不是很好的排序,到一个数组中,它们是你输入到HTML中的原始字符串(这就是为什么即使“红色”也不起作用)。

我建议你使用jQuery一个快速的解决方案

或者你可以这样做:

for (i = 0 ; i < x.length ; i++) { 
    classNames = x[i].style.split(" "); 
    for (var j = classNames.length; j--;) if (colors[classNames[j]]) { 
     x[i].style.backgroundColor = colors[classNames[j]]; 
    } 
} 
0

的代码不会因为你的className属性的精确匹配没有属性。

要解决该问题,请使用String#split方法从类名称中获取第一个类名。

var ar = ["blue", "green", "red"], 
 
    x = document.getElementsByTagName('DIV'), 
 
    i, 
 
    colors = {}; 
 

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

 
for (i = 0; i < x.length; i++) { 
 
    x[i].style.backgroundColor = colors[x[i].className.split(" ")[0]]; 
 
}
.one_in, 
 
.two_in, 
 
.three_in { 
 
    width: 100px; 
 
    height: 100px; 
 
    border: 1px solid #000; 
 
}
<div class="blue one_in"> 
 
</div> 
 
<div class="green two_in"> 
 
</div> 
 
<div class="one_in"> 
 
</div> 
 
<div class="red three_in"></div>

1

因为.className给你的所有类的名称。例如green two_in而你想要的只是​​。因此,你应该添加one_in作为div的id

var ar = ["blue", "green","white", "red"], 
 
    x = document.querySelectorAll('div'),i,colors = {}; 
 

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

 
for (i = 0 ; i < x.length ; i++) { 
 
    x[i].style.backgroundColor = colors[x[i].className]; 
 
}
#one_in,#two_in,#three_in{ 
 
    width:100px; 
 
    height:100px; 
 
    border:1px solid #000; }
<div class="blue" id="one_in"> 
 
</div><div class="green"id="two_in"> 
 
</div><div id="one_in"> 
 
</div><div class="red" id="three_in"> 
 
</div>

+0

r编辑一个不工作/显示。 – 2016-12-26 05:39:35

+0

伙计你在说什么。这是工作。 – ab29007

+0

其白色,自己运行... – 2016-12-26 05:44:46