2011-02-22 30 views
0

我想知道如何在每次計時器重新開始時輸入消息。這裏是我的代碼至今:JavaScript函數重新啓動後,您如何顯示消息?

<head> 
<script type="text/javascript"> 
var c=10; 
var t; 
var timer_is_on=0; 

function timedCount() { 
    document.getElementById('txt').value = c; 
    c = c - 1; 
    if (c == 0) 
     c = 10; 

} 

function doMining() { 
    if (!timer_is_on) { 
     timer_is_on = true; 
     t = setInterval(function() { 
      timedCount(); 
     }, 1000);     
    } 
} 

</script> 

<SPAN STYLE="float:left"> 
<form> 
<input type="button" value="Mining" onClick="doMining()"> 
<input type="text" id="txt"> 
</form> 
</SPAN> 

回答

0

兩個簡單的步驟:

  1. 您的信息展現出來創建一個地方(即其他網絡元素)
  2. 在你的條件,當你的計數器達到0時,更新該消息元素的值

下面是一個例子:

<div id='message'></div> 

然後,訪問該元件並附加消息或使用DOM遍歷(優選使用一個JavaScript框架如dojojquery但也可以做到這一點手動地)修改方法:

if (c == 0) { 
    var _message = document.createTextNode("Timer has finished!"); 
    document.getElementById('message').appendChild(_message); 
    c = 10; 
} 

另外,不要t將SPAN放在表格的周圍。嘗試一個「div」來代替。 Span是用於設計線型文檔元素的樣式。

編輯:我假設當你說「重新開始」時,你的意思是當c = 0或定時器運行10次時。當「重新開始」時也意味着計時器重新調用方法時(即每隔1秒,在這種情況下,您只需將更新代碼放在函數頂部)

+0

好的,謝謝:D生病嘗試一下,感謝提示 – Mason 2011-02-23 06:25:09

+0

OK:P我想這一點,計時器無法啓動 – Mason 2011-02-23 06:30:02

+0

哦,變 「的appendChild(TXT)」 到 「使用appendChild(_message)」。我的錯。 – 2011-02-23 07:14:53

0

您已經在你的「if(c == 0)」中捕獲這個事件。只需添加您需要的額外代碼?

您需要更好地定義重新開始的含義。嘗試將其拉出到自己的方法中,以便您可以單獨使用它。

<script type="text/javascript"> 
var c=10; 
var t; 
var timer_is_on=0; 

function timedCount() { 
    document.getElementById('txt').value = c; 
    c = c - 1; 
    if (c == 0) 
     startOver(); 
} 

function startOver() { 
    alert("Starting Over, Fool!"); 
    c = 10; 
    clearTimeout(t); 
    timer_is_on=0; 
    doMining(); 
} 

function doMining() { 
    if (!timer_is_on) { 
     timer_is_on = true; 
     t = setInterval(function() { 
      timedCount(); 
     }, 1000);     
    } 
} 

</script> 
相關問題