【问题标题】:document.getElementById().value truncating the seconds if it is 0document.getElementById().value 如果为 0,则截断秒数
【发布时间】:2021-02-01 19:50:09
【问题描述】:

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

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

【问题讨论】:

  • 没有足够的上下文来验证或解释您所描述的内容。如果它是一个简单的文本输入字段,则不会发生这种行为。
  • 请以minimal reproducible example的形式显示与问题相关的所有代码(在这种情况下,我们需要知道id为“time”的元素的HTML)。您可以使用 Stack Snippets(图标在编辑器工具栏中看起来像 <>)在 Stack Overflow 上创建一个可运行的示例。
  • 我已经添加了元素的 HTML。够了吗?
  • 嗯,时间表达式 HH:MM 与 HH:MM:00 完全相同。如果您需要零,您可以随时将它们添加到您自己的代码中。
  • 那么问题是该字段是用户输入的,那么我如何检查它是否为 00,当它为 00 时如何将它们添加到代码中?

标签: javascript truncation


【解决方案1】:

这样的事情怎么样?

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

【讨论】:

  • const {target: {value: timeVal = "00:00:00"} = {}} = e || {};const timeVal = e.target.value || "00:00:00"; 的简写,但在 e 或 target 未定义的情况下也提供默认值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2021-05-09
  • 2021-01-03
  • 2018-12-18
  • 2014-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多