document.getElementById().value 如果为 0,则截断秒数

问题描述

我是 javascript 新手,我在以下方面遇到了一些麻烦:

function log_time() {
    let time = document.getElementById("time").value;
    console.log(time);
}
<input class="input-field" type="time" id="time" onchange="log_time()" step="1">

值的格式如下 HH:MM:SS 但是当秒为 00 时,它会被完全截断,结果时间变量变为 HH:MM。

如果秒数被截断,有没有办法防止秒数被截断或检查以格式化值?

解决方法

这样的事情怎么样?

const timeElement = document.getElementById("time")

timeElement.addEventListener('change',(e => {
  // extract e.target.value as timeVal with default value "00:00:00"
  const {target: {value: timeVal = "00:00:00"} = {}} = e || {};

  // extract hours,minutes,seconds from the split array.
  const timeValArray = timeVal.split(":");
  const [hours,seconds = "00"] = timeValArray;

  console.log("hours: ",hours)
  console.log("minutes: ",minutes)
  console.log("seconds: ",seconds)
}
));

输出:

hours:  17
minutes:  13
seconds:  00