0

我试图在将它们中的每一个转换为之后将一个innerHTML值添加到另一个,然后将总数分配给另一个,以便可以使用javascript打印出来innerHTMLintinnerhtml

我试过parseIntand parseFloat,但对我没有用。

实际上,在我转换innerHTML为之后,int我得到了“NaN”而不是一个数字。

这是我的代码:

var Sum = parseInt(document.getElementById('fir').innerHTML) +
          parseInt(document.getElementById('sec').innerHTML);

setTimeout(function func(){ch1.innerHTML=Sum;},2500);

现在Sum函数内的最后一行func()应该是一个整数,但不幸的是它不是,在我的情况下它等于“NaN”,这是为什么呢?

编辑:
关于冷杉和秒的每一件事

<body>
<h1 id="fir"></h1>
<h2 id="sec"></h2>

<script>
  var x = document.getElementById("fir")
  x.style.position = "absolute";
  x.style.left = 770;
  x.style.top = 315;

  var z = document.getElementById("sec")
  z.style.position = "absolute";
  z.style.left = 930;
  z.style.top = 315;

  setTimeout(function a(){x.innerHTML=Math.floor((Math.random()*10)+1);},1000);

  setTimeout(function b(){z.innerHTML=Math.floor((Math.random()*10)+1);},2000);

</script>

</body>
4

1 回答 1

0

尝试从数值开始

    <h1 id="fir">0</h1>
    <h2 id="sec">0</h2>

您在超时之前对值求和,您应该将求和包装在一个函数中,并在设置值示例后立即调用它:

    function applySUM()
    {
        var Sum = parseInt(document.getElementById('fir').innerHTML) +
        parseInt(document.getElementById('sec').innerHTML);    
        ch1.innerHTML=Sum; //removed the timer to apply the calculation
    }

    setTimeout(function(){
        x.innerHTML=Math.floor((Math.random()*10)+1);
        applySUM();
    },1000);

    setTimeout(function(){
        z.innerHTML=Math.floor((Math.random()*10)+1);
        applySUM();
    },2000);
于 2013-08-25T22:45:37.377 回答