循环多维数组以满足jQuery条件

时间:2015-11-29 16:20:58

标签: javascript jquery arrays loops

我有这个数组:

var conditions = [];
    conditions [0] = ["0", "1", "2", "3", "4"];
    conditions [1] = ["5", "6", "7", "8", "9"];
    conditions [2] = ["19", "20", "21", "22"]; 
    conditions [3] = ["13", "14", "15", "16"]; 

我尝试做的是遍历数组,以便当weather.code值(使用jQuery检索)满足数组中的值时,背景颜色将相应地改变。 if语句还没有完成,这只是一个向你展示我的意思的例子:

if(weather.code === **item in conditions[1] for example**) {
   $("#page").css({background: "#F7AC57"}, 1500);
} 
else {
   $('#page').css({background: "#000"}, 1500);
}

有关如何实现这一目标的任何建议将不胜感激。我是JavaScript / jQuery的新手。

1 个答案:

答案 0 :(得分:0)

使用indexOf功能:

if(conditions[1].indexOf(weather.code) != -1) {
   $("#page").css({background: "#F7AC57"}, 1500);
} 
else {
   $('#page').css({background: "#000"}, 1500);
}

对其他人使用相同的内容:

if(conditions[0].indexOf(weather.code) != -1) {
   $("#page").css({background: "#F7AC57"}, 1500);
} 
else {
   $('#page').css({background: "#000"}, 1500);
}
if(conditions[2].indexOf(weather.code) != -1) {
   $("#page").css({background: "#F7AC57"}, 1500);
} 
else {
   $('#page').css({background: "#000"}, 1500);
}
if(conditions[3].indexOf(weather.code) != -1) {
   $("#page").css({background: "#F7AC57"}, 1500);
} 
else {
   $('#page').css({background: "#000"}, 1500);
}

我建议您使用switch语句。