-1

(second.innerHTML) -1 有效,但 (num.innerHTML) -1 无效,为什么?

function doDcrements() {
     var hidden = document.getElementById('hidden');
     var second = document.getElementById('second');  // the second is 20.
     var loopTimer = 0;
     if (second.innerHTML != "0") {
         second.innerHTML = (second.innerHTML) -1;
         second.style.color = "blue";
         loopTimer = setTimeout('doDecrements()',1000);
     }else {
         second.style.color = "grey"; 
         hidden.style.display = "block";   
     }
 } 

..................................................... ..................................................... ..................................................... …………………………………………………………………………

function doDcrements() {
         var hidden = document.getElementById('hidden');
         var second = document.getElementById('second'); // the second is 20. 
         var loopTimer = 0; 
         var num = document.getElementById('num'); // the number is 20. 
         if (second.innerHTML != "0") {
             second.innerHTML = (num.innerHTML) -1;
             second.style.color = "blue";
             loopTimer = setTimeout('doDecrements()',1000);
         }else {
             second.style.color = "grey";  
             hidden.style.display = "block";   
         }
     } 

当我通过 for 循环创建它时,它不会发生:

function doDcrements() {
    var hidden = document.getElementById('hidden');
    var second = document.getElementById('second');
    for (i=20; i<=0; i--) {
           if (second.innerHTML != "0") {
             second.innerHTML = i;
             second.style.color = "blue";
             loopTimer = setTimeout('doDecrements()',1000);
         }else {
             second.style.color = "grey";  
             hidden.style.display = "block";   
         }
    }
}

html代码:

<div id="hidden">started</div>
<p id="second">20</p>
<div onClick="doDcrements();">Download</div> 
4

2 回答 2

2

请查看您的 for 循环:

for (i=20; i<=0; i--) 

i=20 并且 i<=0。它永远不会运行。

于 2012-12-14T10:24:31.763 回答
0

(second.innerHTML) -1 that worked but (num.innerHTML) -1 that not working why?

没有看到你的代码,唯一的猜测是 num.innerHTML 没有给你一个可转换为数字的字符串。例子:

'20' - 1 = 20

'<input name="xyz" val="20"/>' - 1 = NaN

您的 HTML 没有任何 id="num" 的元素。如果是这种情况,num 将为空。

变化
setTimeout(doDecrements,1000);
for (i=20; i >=0; i--)

于 2012-12-14T10:29:24.577 回答