遇到for循环数组检查和JSON变量的麻烦

时间:2013-06-27 20:53:57

标签: javascript jquery json loops for-loop

JS代码

<?php
date_default_timezone_set('America/Los_Angeles');
$date = date('Gi', time());
?>

<script type="text/javascript">
$(function() {
  $(".show_hide").click( function()
       {
    var locTime = <?php echo json_encode($date) ?>; 
$.getJSON( "url_to_json", function(data) {
var isClosed = true;    
    for (var i = 0; i < data.location.monday.length || isClosed; i++) { 
    console.log("sucess1");
    xr_mon= data.location.monday[i];
    console.log("sucess2");
     if (locTime >= xr_mon.kai && locTime < xr_mon.guan ){
        console.log("location is open!");
        isClosed = false; 
        $('.xr').show("drop", { direction: "up" }, 400); 
        }
    else {
        console.log("location is closed");
        $('.xr').hide("drop", {
              direction: "down"
          }, 800);
    }
    }
});
       }
  );
});
</script>

JSON代码

{ "location": 
{
    "monday": [
    {"kai": 700, "guan": 1400},
    {"kai": 1700, "guan": 2100}

    ]
}
}

用这个循环序列进行了几次尝试。

即使isClosed满足条件,我仍然无法弄清楚为什么它仍在循环中。我的代码中是否遗漏了什么?

找到了答案。

<?php
date_default_timezone_set('America/Los_Angeles');
$date = date('Gi', time());
?>

<script type="text/javascript">
$(function() {
  $(".show_hide").click( function()
   {
var locTime = <?php echo json_encode($date) ?>; 
$.getJSON( "url_to_json", function(data) {

for (var i = 0; i < data.location.monday.length; i++) { 
console.log("sucess1");
xr_mon= data.location.monday[i];
console.log("sucess2");
 if (locTime >= xr_mon.kai && locTime < xr_mon.guan ){
    console.log("location is open!");

    $('.xr').show("drop", { direction: "up" }, 400); 
    Break;
    }
else {
    console.log("location is closed");
    $('.xr').hide("drop", {
          direction: "down"
      }, 800);
}
}
});
   }
);
});
</script>

1 个答案:

答案 0 :(得分:0)

如果我理解你的话,(编辑:确实改变了可以)你可以尝试使用'&amp;&amp;'而不是'||'在循环条件下?

for (var i = 0; i < data.location.monday.length && isClosed; i++)

EDIT2: 因为当它是1800时,循环将首先检查:{“kai”:700,“guan”:1400}并且条件不会返回true,因为1800不在700和1400之内。 在第二次尝试{“kai”:1700,“guan”:2100}条件将返回true,因为1800在1700和2100之间。 所以我建议编辑你的脚本this way。 这是你想要完成的吗?

var isClosed = true;    
    xr_mon= data.location.monday[0];
    xr_mon2= data.location.monday[1];
    if ((locTime >= xr_mon.kai && locTime < xr_mon.guan)  || (locTime >= xr_mon2.kai && locTime < xr_mon2.guan) ){
        console.log("location is open!");
        isClosed = false; 
        $('.xr').show("drop", { direction: "up" }, 400); 
        }
    else {
        console.log("location is closed");
        $('.xr').hide("drop", {direction: "down"}, 800);
    }