【问题标题】:how to add to an HTML time element如何添加到 HTML 时间元素
【发布时间】:2017-12-22 17:30:23
【问题描述】:

如何使用 javascript 添加到现有的 HTML 时间元素。我有一个 html 时间元素,希望能够按下一个按钮,将当前时间增加一分钟。我不想使用输入类型时间。这是我现有的代码:

<body>
  <time id = 'time'> 10:00 </time>
  <button onclick = "addTime();">addTime</button>
  <script>
    function addTime(){

      document.getElementById('time').innerHTML += '01:00'
    }
  </script>
</body>

但这只是将时间附加为字符串。有没有简单的方法来解决这个问题?

【问题讨论】:

  • 在你的 javascript 中放一个 Date var,然后操作 Date 对象,即添加一分钟,然后 .toString() 显示

标签: javascript html input time


【解决方案1】:

您可以将Date.prototype.setMinutes() 与元素.innerHTML 的前两个数字一起使用,Date.prototype.setSeconds() 与参数0 一起使用

<body>
  <time id='time'> 10:00 </time>
  <button onclick="addTime();">addTime</button>
  <script>
    const time = document.getElementById('time')
    let date = new Date();   
    
    function addTime() {
      date.setMinutes(1 + +time.innerHTML.match(/\d{2}/)[0]);
      date.setSeconds(0);
      time.innerHTML = String(date).slice(19, 24);
    }
  </script>
</body>

【讨论】:

  • 非常感谢!
【解决方案2】:

在 html 中你可以放这段代码:

 <time id='time'> <label id="hour">10</label>:<label id="second">00</label> </time>
<button onclick="addTime();">addTime</button>

你可以运行这个函数:

function addTime() {
        var h = parseInt(document.getElementById('hour').innerHTML);
        var s = parseInt(document.getElementById('second').innerHTML);
        s++;
        var add = "0";
        if (s < 10) {
            add = "0" + s;
        }
        else {
            add = s;
        }
        if (s == 60) {
            add = "00";
            h = h + 1;
        }
        if (h == 25) {
            h = 1;
        }
        document.getElementById('hour').innerHTML = h;
        document.getElementById('second').innerHTML = add;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 2019-01-06
    • 2021-01-04
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多