你如何每秒加1?

时间:2013-10-30 13:35:20

标签: javascript html css

我已经尝试了一切,我不能这样做! 这是我的代码请帮助:

<!DOCTYPE html>
    <html>
         <head>
              <link rel="shortcut icon" href="favicon.ico"/>
              <title>Doughtnut Box !</title>
              <!--Design-->
              <style>

              </style>
              <!--jQuery and Javascript-->
              <script>
                 var doughnut = 0;
                   window.setInterval(
                        doughnut + 1
                   ,1000);
                   document.getElementById("doughnuts").innerHTML="You have " + doughnut >+ " doughnuts!";
              </script>
         </head>
         <body>
              <h3 id="doughnuts"></h3>
         </body></html>

感谢您的代码,真的很棒!现在我如何保存它以便在刷新时不会重新开始?

5 个答案:

答案 0 :(得分:8)

将它们放入一个功能中。此外,将您的表达式更改为作业

<script>
     var doughnut = 0;
     window.setInterval(
     function () {
         doughnut = doughnut + 1;
         document.getElementById("doughnuts").innerHTML = "You have " + doughnut + " doughnuts!";

     }, 1000);
</script>

下面的Runnable演示:

var doughnut = 0;
window.setInterval(function () {
  doughnut = doughnut + 1;
  document.getElementById("doughnuts").innerHTML = "You have " + doughnut + " doughnuts!";
}, 1000);
<div id="doughnuts"></div>

答案 1 :(得分:2)

setInterval接受函数或引用代码。 试试这个:

<script>
var doughnut = 0;
window.setInterval(function(){
    doughnut++;
    document.getElementById("doughnuts").innerHTML = "You have " + doughnut + " doughnuts!";
}, 1000);
</script>

答案 2 :(得分:1)

试试这个:

var doughnut = 0;
window.setInterval( 
function()
{
    document.getElementById("doughnuts").innerHTML="You have " + ++doughnut + " doughnuts!";
 }
                   ,1000);

答案 3 :(得分:1)

试试这个:

DEMO Here.

var doughnut = 0;
//show 0 for the first time
show_value();
//start counter
setInterval(function(){
    doughnut += 1;
    show_value();        
}, 1000);
function show_value(){
    document.getElementById("doughnuts").innerHTML = "You have " + doughnut + " doughnuts!";
}

答案 4 :(得分:1)

另一种计算时间来完成这项功能的方法。

这种情况无关紧要,但在某些情况下可能有用。

var doughnut = 0;

function show_value()
{
    document.getElementById("doughnuts").innerHTML = "You have " + doughnut++ + " doughnuts!";
    setTimeout(show_value, 1000);
}

show_value();