我有两个名为 arr_o
和 arr_t
的数组
x = document.getElementsByClassName("div"); //simple div width and height is 100px and 100px
for (var i = 0 ; i < x.length ; i++ ){
var arr_o = [one,two,three]; //classes name
for (var j = 0 ; j < arr_o.length ; j++ ){
var arr_t = ["blue","green","red"]; // background color value
for (var l = 0 ; l < arr_t.length ; l++ ){
if(x[i].classname === arr_o[j] ){
x[i].style.backgroundColor = arr_t[l];
}
}
}
}
所以我想制作一个 div 来自动检测类名并分别从两个数组中设置背景颜色
示例
如果类是one
,那么div背景将为“blue”
如果类是two
,那么div背景将为“绿色”
如果类是三
,那么div背景将为“红色”
我应该使用 forEach 循环吗?还有其他方法吗?
最佳答案
您可以使用对象和类名作为键,其中 document.getElementsByTagName
.
var colors = {
one: 'blue',
two: 'green',
three: 'red'
};
x = document.getElementsByTagName("div"); //simple div width and height is 100px and 100px
for (var i = 0 ; i < x.length ; i++ ){
x[i].style.backgroundColor = colors[x[i].classname];
}
关于javascript - 如何自动检测数组中的值并从另一个数组设置背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41250205/