-7

这是我破碎的意大利面条 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);
    });
});

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

4

6 回答 6

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以了解有关定期更新的信息。

于 2012-04-20T17:34:07.180 回答
1

首先,您的 JS 代码看起来有问题。我假设您想要类似的东西

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

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

于 2012-04-20T17:33:01.337 回答
1

您似乎要关闭ready两次通话。

});
于 2012-04-20T17:34:19.007 回答
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);
}​
于 2012-04-20T17:43:23.683 回答
0

你的代码不正确

var d = new Date();
var hours = d.getHours();
var mins = d.getMinutes();
于 2012-04-20T17:32:28.380 回答
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);

});

一个例子。

于 2012-04-20T17:42:39.770 回答