2015-11-29 18 views
0

我有此數組:循環多維數組滿足條件的jQuery

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的新手。

+3

您正在尋找數組原型indexOf()方法:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/global_objects/Array/indexOf –

回答

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聲明這一點。