<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>计时器</title> </head> <script type="text/javascript"> var num=0; var i; var start=document.getElementById('start'); var stop=document.getElementById('stop') start.onclick=function(){ document.getElementById('count').value=num; num=num+1; i=setTimeout("startCount()",1000); } stop.onclick= function(){ clearTimeout(i); } </script> </head> <body> <form> <input type="text" id="count" /> <input type="button" id="start" value="Start" /> <input type="button" id="stop" value="Stop" /> </form> </body> </html> 请问这样为什么不可以?
i=setTimeout("startCount()",1000); 里面startCount() 几个意思?
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>计时器</title> </head> </head> <body> <form> <input type="text" id="count" /> <input type="button" id="start" value="Start"/> <input type="button" id="stop" value="Stop"/> </form> </body> <script type="text/javascript"> var num=0; var i; var start=document.getElementById('start'); var stop=document.getElementById('stop'); start.onclick=function(){ document.getElementById('count').value=num; num=num+1; i=setTimeout("startCount()",1000); } stop.onclick= function(){ clearTimeout(i); } </script> </html>
把script部分放到下面来,你执行脚本的时候,html元素可能还没加载到。
var stop=document.getElementById('stop')后面加个分号看下