Time.Now在没有页面刷新的情况下更新视图(javascript)

时间:2013-05-03 13:31:50

标签: javascript jquery ruby-on-rails ruby-on-rails-3

我试图在页面上简单地显示Time.now,并使用某种Javascript更改分钟。

当然这很容易,但我似乎无法弄清楚我将如何开始这个呢?

<span><%= Time.now.strftime('%H:%M%p %d/%m/%Y') %></span>

2 个答案:

答案 0 :(得分:1)

试试这个:

http://www.w3schools.com/js/tryit.asp?filename=tryjs_setinterval3

    <script>
     var myVar=setInterval(function(){myTimer()},1000);
     function myTimer()
     {
        var d=new Date();
        var t=d.toLocaleTimeString();
        document.getElementById("demo").innerHTML=t;
      }
    function myStopFunction()
     {
    clearInterval(myVar);
      }
     </script>

答案 1 :(得分:1)

请看一下 http://jsfiddle.net/2dJAN/14/

$(document).ready(function() {
    //custom wrote clock
    function updateClock() {
        var currentTime = new Date();
        var currentHours = currentTime.getHours();
        var currentMinutes = currentTime.getMinutes();
        var currentSeconds = currentTime.getSeconds();
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth() + 1;
        var yyyy = today.getFullYear();
        if (dd < 10) {
            dd = '0' + dd
        }
        if (mm < 10) {
            mm = '0' + mm
        }
        var today = mm + '/' + dd + '/' + yyyy ;
        currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
        currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;
        var timeOfDay = (currentHours < 12) ? "AM" : "PM";
        currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
        currentHours = (currentHours == 0) ? 12 : currentHours;
        var currentTimeString = today + "&nbsp;&nbsp;&nbsp;" + currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay ;
        var currentTimeStringforCheckout = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
        $(".clock").html(currentTimeString);
        $(".clock_in_checkout").html(currentTimeStringforCheckout);
    }
    window.onload = updateClock();
    setInterval(function() {
        updateClock();
    }, 1000);

});