setInterval函数不起作用

时间:2016-08-12 06:20:31

标签: javascript jquery

我正在jQuery中进行本地时间观察。我写了一些代码,但它没有用。这是我的代码:

$(document).ready(function(){
    function addZero(i) {
        if (i <= 9) {
            i = "0" + i;
        }
       return i;
    }
    var d = setInterval(function(){
        var z = new Date();
        var h = addZero(z.getHours());
        var m = addZero(z.getMinutes());
        var s = addZero(z.getSeconds();
        var a = '';
        if (h > 11 ) a = "PM" 
        else a = "AM"
        if (h == 16) h = '0'+4
        $('pre').html(h + ":" + m + ":" + s + "&nbsp;" + "a");
    },1000);
});

3 个答案:

答案 0 :(得分:1)

你犯了一些错误 - 检查代码

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
  var d,z,h,m,s,a
  function addZero(i) {
    if (i <= 9) i = "0" + i;
    return i;
  }
  d = setInterval( function(){
    z = new Date();
    h = addZero(z.getHours());
    m = addZero(z.getMinutes());
    s = addZero(z.getSeconds());
    a = '';
    if (h > 11 ) a = "PM" 
    else a = "AM"
    if (h == 16) h = '0'+4
    $('#timer').html(h + ":" + m + ":" + s + "&nbsp;" + a);
  },1000);
});
</script>
<pre id="timer"></pre>

答案 1 :(得分:1)

您错过了一个)

$(document).ready(function(){
  
   function addZero(i) {
     if (i <= 9) {
        i = "0" + i;
     }
  
    return i;
   }
  
  
   var d = setInterval(function(){
   var z = new Date();
   var h = addZero(z.getHours());
   var m = addZero(z.getMinutes());
   var s = addZero(z.getSeconds());
     
   var a = '';
   if (h > 11 ) {
      a = "PM" ;
   }
   else {
      a = "AM";
   }
  
   if (h == 16) {
       h = '0'+4;
   }
    
   $('pre').html(h + ":" + m + ":" + s + "&nbsp;" + a);
  
   },1000);
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>

答案 2 :(得分:0)

请在代码中使用下面的代码,有一个函数var d,它是为setInterval声明的,但我没有看到这个函数被调用。所以从哪里打电话。上面的答案也很正确,但是这里的d,z,h,m,s,a不需要全局变量声明。局部变量也在起作用。

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
  //var d,z,h,m,s,a
  function addZero(i) {
    if (i <= 9) i = "0" + i;
    return i;
  }
  setInterval( function(){
    var z = new Date();
    var h = addZero(z.getHours());
    var m = addZero(z.getMinutes());
    var s = addZero(z.getSeconds());
    var a = '';
    if (h > 11 ) a = "PM" 
    else a = "AM"
    if (h == 16) h = '0'+4
    $('pre').html(h + ":" + m + ":" + s + "&nbsp;" + a);
  },1000);
});
</script>
<pre id="timer"></pre>
&#13;
&#13;
&#13;