开发者

Simple javascript not working - frustrating!

can someone please help me get this simple countdown timer to work, firebug is complaining: document.counter is undefined

<script> 
<!-- 
// 
 var milisec=0 
 var seconds=30 
 document.counter.d2.value='30' 

function display(){ 
 if (milisec<=0){ 
    milisec=9 
    seconds-=1 
 } 
 if (seconds<=-1){ 
    milisec=0 
    seconds+=1 
 } 
 else 
    milisec-=1 
    document.counter.d2.value=seconds+"."+milisec 
    setTimeout("display()",100) 
} 
display() 
--> 
</script开发者_StackOverflow中文版> 


<form name="counter"><input type="text" size="8" 
name="d2"></form> 


indeed, document.counter doesn't exist because your script is being called before the HTML DOM is loaded.

You need to put your JS inside a function that will be invoked onload.

Instead of calling display() put this at the bottom of your script:

window.onload = display;

Also, the <!-- --> comments haven't been needed around JS code for at least 10 years...


Place the form before the script...


Either have the script at the end of the page, or:

window.onload = function() {
   var milisec=0;
    var seconds=30 ;
    document.forms["counter"].elements["d2"].value='30';
}


You might want to move to JQuery to help with cross browser issues
JQuery $(document).ready()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜