2016-07-04 79 views
-3

如何在加載頁面後調用此函數(簡單定時器)?我真的需要你的建議,以最簡單的方式來做到這一點。Javascript。如何在加載頁面後調用此函數(簡單定時器)?

<script> 
 
    //Timer function 
 
function timer(tag, sec) { 
 
    document.getElementById(tag).innerHTML = "<div id= 'inTime'>" + 
 
     (sec/60 >> 0) + 'min ' + sec % 60 + 'sec' + '<br>' + "</div>"; 
 

 

 

 
    if ((sec/60 >> 0) != 0 || (sec % 60) != 0) { 
 
     setTimeout(function() { 
 
     timer(tag, sec); 
 
     }, 1000); 
 
     sec -= 1; 
 
    } else { 
 
     document.getElementById(tag).innerHTML = "Time is over!"; 
 
    } 
 
    } 
 
</script> 
 

 
<div id="timerPlace"></div> 
 
<br> 
 
<br> 
 
<br> 
 
<br> 
 
<!-- Write number of seconds here: onclick="timer('str',...here!...) --> 
 

 
<button class="button" onclick="timer('timerPlace',3600); style.display = 'none'"> <span>Start Test</span> 
 
</button> 
 

 
<!-- Place this div where you whant timer to be. -->

+0

看看這篇文章=> https://learn.jquery.com/using-jquery-core/document-ready/ –

+2

的可能的複製[調用後完成的功能頁面加載](http://stackoverflow.com/questions/11936816/call-a-function-after-complete-page-load) –

回答

1

你的問題並沒有真正說清楚,但如果我得到你的要求,你需要使用window.onload=function(){ /*code here*/ }和代碼會在頁面加載後立即執行。

<script> 
 
    //Timer function 
 
function timer(tag, sec) { 
 
    document.getElementById(tag).innerHTML = "<div id= 'inTime'>" + 
 
     (sec/60 >> 0) + 'min ' + sec % 60 + 'sec' + '<br>' + "</div>"; 
 

 

 

 
    if ((sec/60 >> 0) != 0 || (sec % 60) != 0) { 
 
     setTimeout(function() { 
 
     timer(tag, sec); 
 
     }, 1000); 
 
     sec -= 1; 
 
    } else { 
 
     document.getElementById(tag).innerHTML = "Time is over!"; 
 
    } 
 
    } 
 
window.onload=function(){ 
 
timer('timerPlace',3600); 
 
} 
 
</script> 
 

 
<div id="timerPlace"></div> 
 
<br> 
 
<br> 
 
<br> 
 
<br> 
 
<!-- Write number of seconds here: onclick="timer('str',...here!...) --> 
 

 
<button class="button" onclick="timer('timerPlace',3600); style.display = 'none'"> <span>Start Test</span> 
 
</button> 
 

 
<!-- Place this div where you whant timer to be. -->

+0

是的,這正是我所需要的!非常感謝你,對於令人困惑的解釋感到抱歉。 – Rumata

相關問題