4

我什么都试过了,我做不到!!!这是我的代码,请帮助:

<!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>

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

4

5 回答 5

10

把它们放在一个函数中。另外,将您的表达式更改为 assignment

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

     }, 1000);
</script>

下面的可运行演示:

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

于 2013-10-30T13:37:48.097 回答
2

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

<script>
var doughnut = 0;
window.setInterval(function(){
    doughnut++;
    document.getElementById("doughnuts").innerHTML = "You have " + doughnut + " doughnuts!";
}, 1000);
</script>
于 2013-10-30T13:37:59.717 回答
1

试试这个:

var doughnut = 0;
window.setInterval( 
function()
{
    document.getElementById("doughnuts").innerHTML="You have " + ++doughnut + " doughnuts!";
 }
                   ,1000);
于 2013-10-30T13:38:22.960 回答
1

试试这个:

演示在这里。

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!";
}
于 2013-10-30T13:42:38.560 回答
1

另一种计算执行该功能的时间的方法。

此案例无关紧要,但在某些情况下可能有用。

var doughnut = 0;

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

show_value();
于 2013-10-30T14:50:11.513 回答