Home  >  Q&A  >  body text

javascript - Please tell me about this js case in w3c. I use window.onload to write how to count from 0 after clicking the end button and then clicking the start button.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
    window.onload = function() {
            var a = 0;
            obtn1 = document.getElementById("btn1");
            obtn2 = document.getElementById("btn2");
            obtn1.onclick = function() {
                setTimeout(function rec() {
                    document.getElementById("txt").value = a;
                    a = a + 1;
                    x = setTimeout(rec, 1000)
                }, 1000)
            }
            obtn2.onclick = function() {
                var b = 0;
                setTimeout(document.getElementById('txt').value=0, 0); 
                    clearTimeout(x);
                }
            }
    </script>
</head>

<body>
    <input type="text" name="text" id="txt" />
    <input type="button" id="btn1" value="开始计时!" />
    <input type="button" id="btn2" value="结束计时!" />
</body>

</html>

I learned to write this by myself. What is the problem? After clicking to end, the original number is counted. I hope that when I click to start again, it starts from 0.

PHPzPHPz2712 days ago960

reply all(4)I'll reply

  • 滿天的星座

    滿天的星座2017-05-16 13:28:00

    obtn2.onclick = function() {
                    a = 0;    //需要重新重置开始数字
                    document.getElementById('txt').value=0; 
                    clearTimeout(x);
                    }
                }

    reply
    0
  • 怪我咯

    怪我咯2017-05-16 13:28:00

    Click to end and reload the page!

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-16 13:28:00

    window.onload=function(){
    var a = 0;

            obtn1 = document.getElementById("btn1");
            obtn2 = document.getElementById("btn2");
            txt=document.getElementById('txt');
            obtn1.onclick=function(){
            txt.value=++a;
            }
            obtn2.onclick=function(){
            a=0;
            txt.value=a;
            }

    }

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:28:00

    Just put var a = 0; in the obtn1.onclick function and declare it

    reply
    0
  • Cancelreply