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

吉姆045

我是一名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。

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

sleepystar96

这样的事情怎么样?

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, minutes, seconds = "00"] = timeValArray;

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

输出:

hours:  17
minutes:  13
seconds:  00

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章