Javascript JSON时间比较序列
JS 早餐 l=午餐 d=晚餐 o=打开 c=关闭Javascript JSON时间比较序列,javascript,jquery,html,json,Javascript,Jquery,Html,Json,JS 早餐 l=午餐 d=晚餐 o=打开 c=关闭 我试图让这个脚本在时间落在elseif事件中时工作,并通过jquery操作触发closed location div隐藏。但不知怎的,这个脚本中的逻辑似乎不太好用。使用1 if时效果很好,但随着我添加更多的“else if”,脚本会崩溃。您的JSON有点复杂。以下是我将遵循的策略: { "location": { "monday": [ {"b_o": 700}, {"l_c": 1400}, {"d_o":
我试图让这个脚本在时间落在elseif事件中时工作,并通过jquery操作触发closed location div隐藏。但不知怎的,这个脚本中的逻辑似乎不太好用。使用1 if时效果很好,但随着我添加更多的“else if”,脚本会崩溃。您的JSON有点复杂。以下是我将遵循的策略:
{ "location":
{
"monday": [
{"b_o": 700},
{"l_c": 1400},
{"d_o": 1700},
{"d_c": 2100}
]
}
}
$(函数(){
$(“.show_hide”)。单击(函数(){
var当前_时间=;
$.getJSON(“url到json”,函数(数据){
/**
*假设数组总是有序的
*/
var day=data.location.monday[0],
time_diff=2400,//班次和现在之间的时差
当前_diff,//辅助变量
当前移位;//当前移位
/**
*比较所有班次
*/
用于(白天轮班){
/**
*如果当前时间完全相同
*随着转变,我们发现了转变
*/
如果(当前时间==天[班次]){
时间差=电流差;
当前移位=移位;
打破
}
否则如果(当前时间>日[班次]){
/**
*计算时差
*/
当前_diff=当前_时间-日[班次];
/**
*具有微小时差的换档
*是主动换档吗
*/
if(当前差值<时间差值){
时间差=电流差;
当前移位=移位;
}
}
}
/**
*现在轮班决定了,想想该怎么办
*基于轮班字母:
*
*(b | l | d)|(o | c)
*/
if(shift.match(/b_/)){
//早餐
if(shift.match(/_o/)){
//打开
}
否则{
//封闭的
}
}
else if(shift.match(/l_/)){
//午餐
}
否则{
//晚餐
}
});
});
});
{ "location":
{
"monday": [
{"b_o": 700},
{"l_c": 1400},
{"d_o": 1700},
{"d_c": 2100}
]
}
}
<script type="text/javascript">
$(function(){
$(".show_hide").click(function(){
var current_time = <?php echo intval($date) ?>;
$.getJSON("url_to_json",function(data){
/**
* Assume the array is always ordered
*/
var day = data.location.monday[0],
time_diff = 2400, // Time difference between a shift, and now
current_diff, // Auxiliar variable
current_shift; // The current shift
/**
* Compare all shifts
*/
for (shift in day) {
/**
* If current time is exactly the same
* as the shift, we found the shift
*/
if (current_time == day[shift]) {
time_diff = current_diff;
current_shift = shift;
break;
}
else if (current_time > day[shift]) {
/**
* Calculate the time difference
*/
current_diff = current_time - day[shift];
/**
* The shift with the minor time difference
* is the active shift
*/
if (current_diff < time_diff) {
time_diff = current_diff;
current_shift = shift;
}
}
}
/**
* shift is now determined, think what to do
* based on shift letters:
*
* (b|l|d)_(o|c)
*/
if (shift.match(/b_/)) {
// Breakfast
if (shift.match(/_o/)) {
// Open
}
else {
// Closed
}
}
else if (shift.match(/l_/)) {
// Lunch
}
else {
// Dinner
}
});
});
});