2016-07-04 44 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

相关问题