您好我在这里发帖http://jsfiddle.net/7ztEf/9/解释了我想要实现的目标。
我将其分解,我需要根据数组索引的值填充div bg,这些是1-40之间的4个随机数,比如返回的数字是5,15,25,35。逻辑是如果数字范围1-10,那么div bg是红色,如果11-20然后是蓝色等等
我一直在为此而自杀,真的需要一些建议,这是最好的方式,非常感谢P
function myNumbers(numbers, type) {
for (var x in numbers) {
document.getElementById(type + x).innerHTML = numbers[x];
/*
here I need to query each index value and apply to ball div, ie:
if index 0 numbers > 0) && numbers <= 10 than ball-0 div bg is red
if index 0 numbers > 11) && numbers <= 20 than ball-0 div bg is blue
if index 0 numbers > 21) && numbers <= 30 than ball-0 div bg is orange
if index 0 numbers > 31) && numbers <= 40 than ball-0 div bg is green
repeating for eack index value.
if index 1 numbers > 0) && numbers <= 10 than ball-1 div bg is red
etc
*/
}
}
myNumbers([5,15,25,35],'test - ')
答案 0 :(得分:1)
对于几种颜色,我会这样写出来:
for (var x = 0, n = numbers.length; x != n; ++x) {
var nr = numbers[x],
el = document.getElementById(type + x),
color;
el.innerHTML = nr;
if (nr > 0) {
if (nr <= 10) {
color = 'red';
} else if (nr <= 20) {
color = 'blue';
} else if (nr <= 30) {
color = 'orange';
} else if (nr <= 40) {
color = 'green';
}
}
if (color) {
el.style.color = color;
}
}
答案 1 :(得分:1)
试试这个..
for (var x = 0;x<numbers.length;x++) {
el = document.getElementById(type + x);
el.innerHTML = nr;
if (nr > 0) {
if (nr <= 10) {
color = 'red';
} else if (nr <= 20) {
color = 'blue';
} else if (nr <= 30) {
color = 'orange';
} else if (nr <= 40) {
color = 'green';
}
}
if (color) {
document.getElementById('ball-' + x).style.backgroundColor = color;
}
}
答案 2 :(得分:0)
我会做这样的事情:
var colors = ['red', 'blue', 'orange', 'green'];
function myNumbers(numbers, type) {
for (var i = 0; i < numbers.length; i++) {
var number = numbers[i];
var color = colors[Math.floor(number / colors.length)];
document.getElementById(type + i).innerHTML = number;
document.getElementById('ball-' + i).style.backgroundColor = color;
}
}
不要使用for...in
语法迭代数组。这会迭代对象的属性。