我的span标签没有更新

我的span标签没有更新

如果小时

function showTime(){
    const date = new Date();
    const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    let d = document.getElementById("day").innerHTML = days[date.getDay()];
    let h = document.getElementById("hour").innerHTML = date.getHours();
    let m = document.getElementById("minute").innerHTML = date.getMinutes();
    let s = document.getElementById("second").innerHTML = date.getSeconds();


    if(h == 0){
      h = 12;
    }

    if(h > 12){
      h -= 12
    }

    h = h < 10 ? "0"+h :h;
    m = m < 10 ? "0"+m :m;
    s = s < 10 ? "0"+s :s;


    setTimeout(showTime, 1000);
    console.log(m);
}

showTime();

最佳答案

在计算之后而不是之前设置跨度元素的innerHTML

这是使用三进制而不是if语句和pad函数的固定和简化版本:



function showTime(){
    const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    const date = new Date();
    let h = date.getHours();
    let m = date.getMinutes();
    let s = date.getSeconds();

    const pad = x => x < 10 ? '0' + x : x;

    h = h === 0 ? 12 : h;
    h = h > 12 ? h - 12 : h;

    document.getElementById("day").innerHTML = days[date.getDay()];
    document.getElementById("hour").innerHTML = pad(h);
    document.getElementById("minute").innerHTML = pad(m);
    document.getElementById("second").innerHTML = pad(s);

    setTimeout(showTime, 1000);
}

showTime();

<span id="day"></span>&nbsp;
<span id="hour"></span>:<span id="minute"></span>:<span id="second"></span>

关于javascript - 附加0或将时钟的0更改为12时,我的span标签没有更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55075189/

10-13 03:35