单击格式更改按钮可在1秒钟的时间内提供24小时和12小时格式。这可能是由于我的代码中出现某些逻辑错误,我无法弄清。
const clock = document.querySelector('.time');
const date_data = document.querySelector('.date');
const day_display = document.querySelector('.day');
const format = document.querySelector('.format');
const tick_24 = () => {
const now = new Date();
const h = now.getHours();
const m = now.getMinutes();
const s = now.getSeconds();
const html = `
<span>${h}</span> :
<span>${m}</span> :
<span>${s}</span>
`;
clock.innerHTML = html;
}
const tick_12 = () => {
const now = new Date();
const h = 30;
const m = now.getMinutes();
const s = now.getSeconds();
let hour;
if (h > 12) {
hour = h - 12;
} else {
hour = h;
}
const html = `
<span>${hour}</span> :
<span>${m}</span> :
<span>${s}</span>
`;
clock.innerHTML = html;
}
const day_disp = () => {
const now2 = new Date();
const day = now2.getDay();
let real_day = "";
if (day === 0) {
real_day = "Sun";
} else if (day === 1) {
real_day = "Mon";
} else if (day === 2) {
real_day = "Tue";
} else if (day === 3) {
real_day = "Wed";
} else if (day === 4) {
real_day = "Thu";
} else if (day === 5) {
real_day = "Fri";
} else {
real_day = "Sat";
}
const html = `${real_day}`;
day_display.innerHTML = html;
}
const date_dis = () => {
const now1 = new Date();
const date_log = now1.getDate();
const month = now1.getMonth();
const year = now1.getFullYear();
const html1 = `
<span>${date_log}</span> :
<span>${month+1}</span> :
<span>${year}</span>
`;
date_data.innerHTML = html1;
}
// const timer = () => setInterval(tick_12, 1000);
// timer();
let check = true;
const funct = () => {
const timer1 = () => setInterval(tick_24, 1000);
const timer2 = () => setInterval(tick_12, 1000);
if (check === true) {
timer1();
clearInterval(timer2);
check = false;
} else {
timer2();
clearInterval(timer1);
check = true;
}
}
format.addEventListener('click',() => {
funct();
})
const func = () => {
date_dis();
day_disp();
}
setInterval(func, 1000);
预期结果是,它必须在一次单击时显示24小时格式,而在另一次单击时显示12小时格式,并且必须切换,但它不起作用!