首页 > 解决方案 > 将分钟添加到输入表单中的当前时间

问题描述

我在输入中有这个当前时间码:

<!DOCTYPE html>
<html>
<body onload="sum()">
  Current Time: <input type='time' value='now' readonly disabled>
  <script src='scripts/jquery.min.js'></script>
  <script id="rendered-js">
  $(function () {
    var d = new Date(),
    h = d.getHours(),
    m = d.getMinutes();
    if (h < 10) h = '0' + h;
    if (m < 10) m = '0' + m;
    $('input[type="time"][value="now"]').each(function () {
      $(this).attr({ 'value': h + ':' + m });
    });
  });
  </script>  
</body>
</html>

如何从另一个输入字段添加分钟?示例:下午 2:00 + 00:30 分钟 = 下午 2:30

它必须在输入字段中

标签: javascripthtmltime

解决方案


这可以通过setMinutes属性来完成。

在此处阅读更多信息:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes

但是您需要维护对原始日期的引用,重新计算,然后更新 DOM。像这样的东西:

$(function () {
  var d = new Date(),
  h = d.getHours(),
  m = d.getMinutes();
  if (h < 10) h = '0' + h;
  if (m < 10) m = '0' + m;
  $('input[type="time"][value="now"]').each(function () {
    $(this).attr({ 'value': h + ':' + m });
    // attach this event to the input controlling the minutes: 
    $(this).addEventListener('change', e => {
      // set the minutes
      d.setMinutes(e.target.value)
      // update the minutes variable
      m = d.getMinutes()
      // update the HTML attribute to reflect the new value
      $(this).attr({ 'value': h + ':' + m });
    })
  });
});

让我知道这是否有帮助。


推荐阅读