自动刷新输入时间对象,无需重新加载页面

Auto Refresh Input Time object without reloading page

本文关键字:新加载 加载 输入 刷新 时间 对象      更新时间:2023-09-26

我有一个输入字段,我想每 2 秒左右刷新一次。但是,我似乎无法正确获得"setInterval",因为它没有更新我的ID。 我不应该使用 ID 来声明刷新?任何帮助将不胜感激。

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8" content="HTML,CSS,XML,JavaScript">
      <script src="Scripts/Global.js" type="text/javascript"></script>
      <script src="Scripts/jquery.js" type="text/javascript"></script>    
      <link rel="stylesheet" type="text/css" href="Styles/Design.css">
   </head>
   <body>
      Time: &nbsp;<input type="time" id="theTime">
      <script type="text/javascript"
         src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
      <script>
         var myVar = setInterval(function(){ myTimer() }, 1000);
         function myTimer() {
            var d = new Date();
            var t = d.toLocaleTimeString();
            document.getElementById("theTime").innerHTML = t;
         }
      </script>
      <script type="text/javascript">
         $(document).ready( function() {
                            var now = new Date();
                            //now2 prevents the milliseconds from showing up in the input
                            var now2 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours()-8, now.getMinutes(), now.getSeconds());
                            $('#theTime')[0].valueAsDate = now2;
                        });
      </script>
    </body>
</html>

您正在设置 myTimer 的innerHTML,您实际上应该在其中设置valueAsDate,就像在$(document).ready函数中一样。

以下是myTimer的外观:

function myTimer() {
   var now = new Date();
   var now2 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours()-8, now.getMinutes(), now.getSeconds());
   $('#theTime')[0].valueAsDate = now2;
}

然后,您可以从$(document).ready内呼叫myTimer()

$(document).ready( function() { 
  myTimer();
});

您正在尝试设置输入字段的内部 HTML。 请改用$('#theTime').val()