让时间自动出现在输入类型=“时间”中

Have Time automatically be in the input type="time"

本文关键字:时间 类型 输入      更新时间:2023-09-26

我试图在加载页面时将当前时间显示为输入中的值。但是,由于某种原因,它不起作用。有什么建议吗?感谢您的任何帮助。

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <script src="Scripts/Global.js"></script>
      <script src="Scripts/jquery.js"></script>   
      <link rel="stylesheet" type="text/css" href="Styles/Design.css">
   </head>
   <body>
      <input type="time" id="theTime">
      <script>
         $(document).ready( function() {
          var current = new Date();
          var minute = (now.getMinutes() + 1);               
          var seconds = now.getSeconds();
          if(minute < 10) 
              minute = "0" + minute;
          if(seconds < 10) 
              seconds = "0" + seconds;
          var today = now.getFullYear() + '-' + minute + '-' + seconds;
          $('#theTime').val(today);
         });
      </script>
   </body>
</html>

使用

var now = new Date();

而不是

 var current = new Date();

使用 valueAsDate 使输入显示值

  <body>
      <input type="time" id="theTime">
      <script>
          $(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(), now.getMinutes(), now.getSeconds());
              $('#theTime')[0].valueAsDate = now2;
          });
      </script>
  </body>

你使用了错误的变量使用current

$(document).ready( function() {
          var current = new Date();
          var minute = (current.getMinutes() + 1);               
          var seconds = current.getSeconds();
          if(minute < 10) 
              minute = "0" + minute;
          if(seconds < 10) 
              seconds = "0" + seconds;
          var today = current.getFullYear() + '-' + minute + '-' + seconds;
          $('#theTime').val(today);
         });

在此处查看工作代码

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <script src="Scripts/Global.js"></script>
      <script src="Scripts/jquery.js"></script>   
      <link rel="stylesheet" type="text/css" href="Styles/Design.css">
   </head>
   <body>
      <input type="time" id="theTime">
      <script>
         $(document).ready(function() {
          let now = new Date();
          $('#theTime').val(now.getHours()+":"+ now.getMinutes());
         });
      </script>
   </body>
</html>