javascript js代码在控制台中运行,而不是由实时服务器运行

4zcjmb1e  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(96)

我是js中的biginner程序员。我正在尝试做一个计数器直到100。给定的代码在控制台中工作正常,但计数器在浏览器中通过实时服务器发送工作。

var count=1;
setInterval(()=>{
    if(count!=100)
    {
         count++;
         k.innerHTML=count  
    }
},10)
    • 超文本标记语言**
<html>
<head>
<style>
        body{
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            height: 80vh;
        }
    </style>
</head>
<body>
    <p onclick="hell()">counter</p>
    <div><span id="oe">1</span>
        <i class="fa-solid fa-play"></i>
    </div>
</body>
</html>

倒计时达到100。它在浏览器中工作完美。

xriantvc

xriantvc1#

试试这个:

let count=0;
        let timer = 1;
        let k = null;
        let para = null;
        document.addEventListener("DOMContentLoaded", onDomContentLoaded);
        function onDomContentLoaded(e){
            k = document.getElementById("oe");
            para = document.getElementById("myParagraph");
            para.addEventListener("click",hell);
        }
        function countFunction(){
            if(count<100){
                count++;
                console.log(count);
                k.innerHTML=count;
            }
            if(count===100){
                clearInterval(timer);
                count = 0;
            }
        }
        function hell(){
            if(count===0){
                timer = setInterval(countFunction,10);
            }
        }
body{
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            height: 80vh;
        }
<p id="myParagraph">counter</p>
        <div><span id="oe">1</span>
            <i class="fa-solid fa-play"></i>
        </div>

相关问题