<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>计时器</title>
<script type="text/javascript">
var num=0;
var i;
function startCount(){
document.getElementById('count').value=num;
num=num+1;
i=setTimeout("startCount()",1000);
}
var v=clearTimeout(i);
document.getElementById("f").Onclick="v"
</script>
</head>
<body>
<form>
<input type="text" id="count" />
<input type="button" value="Start" Onclick="startCount()" />
<input type="button" value="Start" id="f"/>
</form>
</body>
</html>
你这个问题有点多,首先你应该讲script标签放在body的最下面,因为script运行时,dom还没有渲染,就不能运行,onclick应该都是小写,而且应该给onclick赋值一个函数,在函数里面运行程序语句,
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>计时器</title> </head> <body> <form> <input type="text" id="count" /> <input type="button" value="Start" Onclick="startCount()" /> <input type="button" value="Stop" id="f"/> </form> <script type="text/javascript"> var num=0; var i; function startCount(){ document.getElementById('count').value=num; num=num+1; i=setTimeout("startCount()",1000); } document.getElementById("f").onclick=function(){ clearTimeout(i); }; </script> </body> </html>
看了你的代码我有启发,根据你的代码我也写了一下,仅供参考!
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>计时器</title>
<script type="text/javascript">
var num=0;
var i;
function startCount(){
document.getElementById('count').value=num;
num++;
i=setTimeout("startCount()",1000);
}
function stopCount(){
clearTimeout(i);
}
</script>
</head>
<body>
<form>
<input type="text" id="count" />
<input type="button" value="Start" onclick="startCount()" />
<input type="button" value="stop" id="f" onclick="stopCount()"/>
</form>
</body>
</html>
clearTimeout()是个方法