0

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>
4

1 回答 1

0

如果我理解正确,(编辑:did 改为 can)你可以尝试使用 '&&' 而不是 '||' 在循环条件下?

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 之间。所以我建议这样编辑你的脚本。是你想要完成的吗?

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);
    }
于 2013-06-27T21:11:29.493 回答