首页 > 解决方案 > 如何根据一天中的时间更改 HTML 按钮的输出?

问题描述

我已将点击计数器设置为在一天中的不同时间工作。我试图让计数器都从相同的 HTML 输入响应,在我的例子中它是一个按钮。本质上,如果在 timeN 期间按下按钮(如下所示),则应通过 Slot 1 输出。如果在此期间未单击,则应通过 Slot 3 输出。

我已经有不同计数器的代码,并且一天中的时间设置为变量。我尝试以类似于下面示例中所示的方式调用它们:

<html lang="en">
<head>
<title>Document</title>
<script type="text/javascript">

    let Slot1Cntr = document.getElementById('SL1').innerHTML;
    let Slot2Cntr = document.getElementById('SL2').innerHTML;
    let Slot3Cntr = document.getElementById('SL3').innerHTML;

    function addCntS1(){
            Slot1Cntr++;
            document.getElementById('SL1').innerHTML = Slot1Cntr;  
    };
    function addCnt2(){
            Slot2Cntr++;
            document.getElementById('SL2').innerHTML = Slot2Cntr;  
    };
    function addCnt3(){
            Slot3Cntr++;
            document.getElementById('SL3').innerHTML = Slot3Cntr;  
    };

    const timeN = now.getHours() === 19;
    const timeNN = now.getHours() === 20; 

    function switchCounter() {
            if (timeN) {
                return addCntS1();
            } else if (timeNN) {
                return addCntS2();
            } else {
                return addCnt3();
            };
        };

</script>
</head>
<body>
    <div>
        <button onClick="switchCounter()" type="submit">Destruct Earth</button>
            <h1><i>Slot 1</i></h1>
            <h1><span id="SL1">0</span></h1>

            <h1><i>Slot 2</i></h1>
            <h1><span id="SL2">0</span></h1>

            <h1><i>Slot 3</i></h1>
            <h1><span id="SL3">0</span></h1>
    </div>
</body>
</html>

除非时间与 const 的 timeN 和 timeNN 对齐,否则我希望按下 Destruct Earth 按钮产生“Slot 3”,分别是晚上 7 点和晚上 8 点。对于任何反馈,我们都表示感谢

标签: javascripthtmlbuttontime

解决方案


我用你的javascript做了这个,它对我有用。

let Slot1Cntr = "";
let Slot2Cntr = "";
let Slot3Cntr = "";

window.onload=function(){
      Slot1Cntr = document.getElementById('SL1').innerHTML;
      Slot2Cntr = document.getElementById('SL2').innerHTML;
      Slot3Cntr = document.getElementById('SL3').innerHTML;
    }    

    function addCntS1(){
            Slot1Cntr++;
            document.getElementById('SL1').innerHTML = Slot1Cntr;  
    };
    function addCnt2(){
            Slot2Cntr++;
            document.getElementById('SL2').innerHTML = Slot2Cntr;  
    };
    function addCnt3(){
            Slot3Cntr++;
            document.getElementById('SL3').innerHTML = Slot3Cntr;  
    };

    var now = new Date();

    const timeN = now.getHours() === 19;
    const timeNN = now.getHours() === 20; 

    function switchCounter() {
            if (timeN) {
                return addCntS1();
            } else if (timeNN) {
                return addCntS2();
            } else {
                return addCnt3();
            };
        };

推荐阅读