javascript - 使用 array 和 object 为可逆可重复 div 着色背景

标签 javascript arrays object

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

为什么这不再起作用,我想用数组和对象中提到的 div class 为 div 着色,我知道它很简单问题给你,可能是个小错误

https://jsfiddle.net/qothk6g3/3/

最佳答案

您在属性前面缺少 color,数组中的一项为 property accessor .

var ar = ["one_in", "two_in", "three_in"],
    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 { width:100px; height:100px; border:1px solid #000; }
<div class="one_in"></div><div class="two_in"></div>

关于javascript - 使用 array 和 object 为可逆可重复 div 着色背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41323573/

相关文章:

javascript - 在 NodeJS 中 fork

c++ - 带有指向数组指针的程序重新分配

php - 如何从表中选择用于数组的运算符

java - 什么是泛型的 C++ 等价物?

javascript - 在 jQuery 中查找下一个元素

javascript - 从 url 中去除哈希值

javascript - Rails 网络应用程序 : Rack app error handling request { GET/packs/js/application-682c14949987e19a8380. js }

javascript - 为什么我的对象在控制台中的表达方式与通过 Tidy JS 运行时的表达方式不同?

r - 在 R 中通配数据框或其他对象

java - 获取对象调用方法