- HTML code
<html><body><input type="text" id="clock" size="35" onblur="float()" onfocus="empty()"/><script language=javascript> var int=self.setInterval("clock()",3000); var t = document.getElementById("clock").value; function clock(){ var content = new Array(); content[0] = "高一"; content[1] = "高二"; content[2] = "高三"; content[3] = "高四"; content[4] = "高五"; for (i=0;i<content.length;i++){ if(t == content[i]){ if(i<4){ t = content[i+1]; }else{ t = content[0]; } } } } function empty(){ document.getElementById("clock").value=""; } function float(){ if(document.getElementById("clock").value == ""){ document.getElementById("clock").value=t; } else{ int=window.clearInterval(int); } }</script></form><button onclick="int=window.clearInterval(int)">Stop interval</button></body></html>我自己写的代码如下,为什么不行啊,请高手指点一下,是js中不像java没有成员变量和局部变量的区别吗
------解决方案--------------------
楼主有两个小错误:
1、var t = document.getElementById("clock").value; 不能直接取value,否则就得不到最新值了;
2、没处理初始状态,也就是一开始clock控件的value是空的情况;
修改如下:
- JScript code
var int = self.setInterval("clock()",1000); var t = document.getElementById("clock"); function clock(){ var content = new Array(); content[0] = "高一"; content[1] = "高二"; content[2] = "高三"; content[3] = "高四"; content[4] = "高五"; if (t.value == "") { t.value = content[0]; } else { for (i=0;i<content.length;i++){ if(t.value == content[i]){ if(i<4){ t.value = content[i+1]; break; }else{ t.value = content[0]; break; } } } } }