gpt4 book ai didi

javascript - 使我的 LiveTime 对象成为文字

转载 作者:行者123 更新时间:2023-12-03 11:34:44 25 4
gpt4 key购买 nike

这是我以前的代码,运行良好:

var todayTime = new Date();
(function updateClock() {
todayTime.setTime(todayTime.valueOf() + 1000);

// In 2 digit format.
document.getElementById("hours").innerHTML = ("0" + todayTime.getHours()).slice(-2);
document.getElementById("minutes").innerHTML = ("0" + todayTime.getMinutes()).slice(-2);
document.getElementById("seconds").innerHTML = ("0" + todayTime.getSeconds()).slice(-2);

setTimeout(updateClock, 1000);
})();

我尝试将其更改为对象文字,以便我可以以更好的方式与其交互。

我在这里想做的是在定义 LiveTime 对象时自动执行 start()

还需要跟踪超时 ID,以便每当我调用 stop() 方法时都可以使用它。

var LiveTime = {
element: document.getElementById("current-time"),
date: new Date(),
timeoutId: 0,

start: (function() {
LiveTime.timeoutId = setTimeout(function() {
LiveTime.date.setTime(LiveTime.date.valueOf() + 1000);

LiveTime.element.innerHTML = ("0" + LiveTime.date.getHours()).slice(-2) + ":"
+ ("0" + LiveTime.date.getMinutes()).slice(-2) + ":"
+ ("0" + LiveTime.date.getSeconds()).slice(-2);
}, 1000);
})(),

stop: function() {
clearTimeout(LiveTime.timeoutId);
}
}

不幸的是,代码给了我一堆未定义错误。

Uncaught TypeError: Cannot set property 'date' of undefined

我做错了什么,如何解决这个问题以及我的代码中的其他问题?

最佳答案

您将 start 定义为自执行函数。这意味着当创建 LiveTime 对象时,start 将被设置为该函数的结果。但由于该函数在 LiveTime 仍在创建时正在运行,因此 LiveTime 是未定义的。将开始定义更改为

start: function() {
LiveTime.timeoutId = setTimeout(function() {
LiveTime.date.setTime(LiveTime.date.valueOf() + 1000);

LiveTime.element.innerHTML = ("0" + LiveTime.date.getHours()).slice(-2) + ":"
+ ("0" + LiveTime.date.getMinutes()).slice(-2) + ":"
+ ("0" + LiveTime.date.getSeconds()).slice(-2);
}, 1000);
},

它应该可以工作(这仍然是您的代码,没有检查可能存在的任何其他错误)

关于javascript - 使我的 LiveTime 对象成为文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26569778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com