<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>计时器</title>
<script type="text/javascript">
var num=0;
function startCount() {
document.getElementById('count').value=num;
num=num+1;
setTimeout("startCount()",1000);
}
startCount();
</script>
</head>
<body>
<form>
<input type="text" id="count" />
</form>
</body>
</html>
这是由于在你刚开始的时候网页还没有加载完毕,id为 "count"的控件还没有加载好,然后你直接执行startCount()方法,该方法里的document.getElementById("count")获取到的对象为null;所以要想有效果,应该在函数后面不执行startCount(),应该执行setTimeout("startCount()",1000)设置一个延时等待的网页的加载。
<!DOCTYPE html>
<html>
<head>
<title> 事件</title>
<script type="text/javascript">
function count(){
var oTxt1 = document.getElementById("txt1").value;
var oTxt2 = document.getElementById("txt2").value;
var oSlt = document.getElementById("select").value;
var result = "";
switch(oSlt) {
case "+":
result = parseFloat(oTxt1) + parseFloat(oTxt2);
break;
case "-":
result = parseFloat(oTxt1) - parseFloat(oTxt2);
break;
case "*":
result = parseFloat(oTxt1) * parseFloat(oTxt2);
break;
default:
result = parseFloat(oTxt1) / parseFloat(oTxt2);
}
document.getElementById("fruit").value = result;
}
</script>
</head>
<body>
<input type='text' id='txt1' />
<select id='select'>
<option value='+'>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type='text' id='txt2' />
<input type='button' value=' = ' onclick=count() /> <!--通过 = 按钮来调用创建的函数,得到结果-->
<input type='text' id='fruit' />
</body>
</html>