我一直在开发一个小时钟应用程序,它可以在加载时显示标准时间,并有一个切换按钮,可以将显示更改为军用时间。但是,我希望使用切换开关,能够在标准时间和军用时间之间来回切换。
如您所见,每次单击按钮,它就不切换到军用时间,还在标准时间和军用时间之间不断地来回走。
有什么办法解决吗?
const headClock = document.createElement("h2");
const dateDay = document.createElement("h2");
const time = document.createElement("h1");
const changeTimeFormat = document.createElement("button");
const div = document.createElement("div");
div.style.cssText = "text-align: center";
headClock.innerHTML = "A Simple Digital Clock";
const weekday = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
const month = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
var isOppen = false;
let myInterval12 = setInterval(timeFor12, 1000);
function timeFor12() {
isOppen = true;
time.innerHTML = new Date().toLocaleString("ru-RU", {
hour12: true,
timeZone: "Asia/Riyadh",
// hourCycle: `${hourCycle}`,
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
}
function timeFor24() {
isOppen = false;
time.innerHTML = new Date().toLocaleString("ru-RU", {
hour12: false,
timeZone: "Asia/Riyadh",
// hourCycle: `${hourCycle}`,
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
}
const today = new Date();
dateDay.innerHTML = `${weekday[today.getDay()]}, ${
month[today.getMonth()]
} ${today.getDay()}th ${today.getFullYear()}`;
changeTimeFormat.onclick = () => {
console.log(isOppen)
if (isOppen === true) {
let myInterval24 = setInterval(timeFor24, 1000);
clearInterval(myInterval24);
setInterval(timeFor12, 1000);
isOppen = false;
} else if (isOppen === false){
clearInterval(myInterval12);
setInterval(timeFor24, 1000);
isOppen = true;
}
// isOppen ? timeFor24() : timeFor12();
};
changeTimeFormat.innerHTML = `Switch to Military Time Format`;
div.appendChild(headClock);
div.appendChild(time);
div.appendChild(dateDay);
div.appendChild(changeTimeFormat);
document.body.appendChild(div);
2条答案
按热度按时间cbjzeqam1#
您可以按如下方式大大简化代码:
请注意,您还需要确保更新日期字符串,以便在一年中的日期发生变化时,该字符串仍然正确。
4c8rllxm2#
这个代码片段是代码的简化。它使用event delegation来处理按钮点击。时钟在递归函数中使用
setTimeout
来“运行”。要检索12/24小时制的日期字符串,它使用区域设置的hc
扩展。有关更多信息,请参见MDN。时间字符串的“state”保存在时间元素的data-attribute中。
代码片段中的所有步骤都包含注解,以便(希望)使事情更清楚一些。
如果您想使用更多的日期时间格式,也许我的小formatting module会很有用。
第一个