你如何使用JavaScript制作工作时钟?

时间:2012-04-20 17:30:29

标签: javascript jquery clock

这是我破碎的意大利面条JavaScript / jQuery代码:

$(document).ready(function(){
    var d = new Date;
    var hours = Date.getHours();
    var mins = Date.getMinutes();
    if(hours > 12){
        var hour = (hours - 12);
        var ampm = "PM";
    }
    else{
        var hour = hours;
        var ampm = "AM";
    }
    var time = hour + ":" + mins, ampm
    $("h1").html(time);
    });
});

你能帮我制作一个工作时钟吗?

6 个答案:

答案 0 :(得分:3)

评论中提到的修正:

$(document).ready(function(){
    var d = new Date;
    var hours = d.getHours(); // call methods on your instance d
    var mins = d.getMinutes();
    if (hours > 12) {
        var hour = (hours - 12);
        var ampm = "PM";
    }
    else {
        var hour = hours;
        var ampm = "AM";
    }
    var time = hour + ":" + mins + ampm; // string concatenate ampm
    $("h1").html(time);
});​ // removed extraneous });

这将在每个h1标记中显示一次的当前时间。请查看setInterval,了解如何定期更新。

答案 1 :(得分:1)

首先,你的JS代码看起来很麻烦。我假设你想要像

这样的东西
var d = new Date();
var hours = d.getHours();
var mins = d.getMinutes();
...
var time = hour + ":" + mins + ", " + ampm;

对于时钟,您需要一个间隔...当前代码仅生成当前时间戳

答案 2 :(得分:1)

您似乎正在关闭对ready两次的通话。

});

答案 3 :(得分:1)

这将创建一个在DOM准备就绪后每秒更新一次的时钟:

$(document).ready(function(){
    updateTime();
    clock = window.setInterval(updateTime, 1000);
});
function updateTime() {
    var d = new Date;
    var hours = d.getHours();
    var mins = d.getMinutes();
    var secs = d.getSeconds();
    if(hours > 12){
        var hour = (hours - 12);
        var ampm = "PM";
    }
    else{
        var hour = hours;
        var ampm = "AM";
    } 
    var time = hour + " : " + mins + ' ; ' + secs + ' ' + ampm;
    $("h1").html(time);
}​

答案 4 :(得分:0)

您的代码不正确

var d = new Date();
var hours = d.getHours();
var mins = d.getMinutes();

答案 5 :(得分:0)

时间会更新

$(document).ready(function(){
    function getTime()
    {
        var d = new Date;
        var hours = d.getHours();
        var mins = d.getMinutes();
       if(hours > 12)
       {
           var hour = (hours - 12);
           var ampm = "PM";
       }
       else
       {
           var hour = hours;
           var ampm = "AM";
       }
       return hour + ":" + mins+ampm;
    }

    setInterval(function(){ // Time will be updated
        $("h1").html(getTime())
    }, 500);

});

An example.