以下代码是javascript 数组的一个实例,目的是让表单上的文本框实现动态效果,原来文本框中默认有个值,如:您的姓名(灰色),意在提示,鼠标点击之后默认值消失,若焦点离开(鼠标点别的地方),又会出现默认值。
而其中有多个文本框,像“您的姓名”,“您的邮箱”,“您的需求等”,原来要实现效果代码如下:
<script language="javascript">
var s=document.getElementById("name");
s.onfocus=function(){if(this.value==this.defaultValue)this.value=''};
s.onblur=function (){if(/^\s*$/.test(this.value)){this.value=this.defaultValue;this.style.color='#aaa'}}
s.onkeydown=function(){ this.style.color='#333'}
var k=document.getElementById("email");
k.onfocus=function(){if(this.value==this.defaultValue)this.value=''};
k.onblur=function (){if(/^\s*$/.test(this.value)){this.value=this.defaultValue;this.style.color='#aaa'}}
k.onkeydown=function(){ this.style.color='#333'}
var j=document.getElementById("web");
j.onfocus=function(){if(this.value==this.defaultValue)this.value=''};
j.onblur=function (){if(/^\s*$/.test(this.value)){this.value=this.defaultValue;this.style.color='#aaa'}}
j.onkeydown=function(){ this.style.color='#333'}
var t=document.getElementById("txt");
t.onfocus=function(){if(this.value==this.defaultValue)this.value=''};
t.onblur=function (){if(/^\s*$/.test(this.value)){this.value=this.defaultValue;this.style.color='#aaa'}}
t.onkeydown=function(){ this.style.color='#333'}
</script>
现在通过javascrip Array数组功能来简化:
<script language="javascript">
var allElem = new Array();
allElem.push('name');
allElem.push('email');
allElem.push('web');
allElem.push('txt');
for (var i=0; i<allElem.length; i++) {
var elem = document.getElementById(allElem[i]);
elem.onfocus=function(){if(this.value==this.defaultValue)this.value=''};
elem.onblur=function (){if(/^\s*$/.test(this.value)){this.value=this.defaultValue;this.style.color='#aaa'}}
elem.onkeydown=function(){ this.style.color='#333'}
}
</script>
两种实现的效果是一样的。