13-函数的封装和复用
//为何使用函数?
//能够对代码进行复用:只要定义一次代码,就可以多次使用它。
//能够多次向同一函数传递不同的参数,以产生不同的结果。
<div>
<input type="text" placeholder="请输入姓名" id="name" /><span>姓名不能为空</span>
</div>
<div>
<input type="text" placeholder="请输入手机号" class="phone" /><span>手机号不能为空</span>
</div>
//封装选择器
function $(name){
//return document.getElementById(name);
return document.querySelector(name);
};
var _name = $("#name"),
_phone = $(".phone");
//成为焦点
_name.onfocus = function(){
this.nextSibling.style.display="none";//紧邻的同级样式隐藏 //nextSibling返回某个元素之后紧邻的节点
};
_phone.onfocus = function(){
this.nextSibling.style.display="none";//紧邻的同级样式隐藏
};
//失去焦点
_name.onblur = function(){
isEmpty(this);
};
_phone.onblur = function(){
isEmpty(this);
};
//公共的判断方法
function isEmpty(cur){ //cur = this
if(cur.value==''){
cur.nextSibling.style.display="inline"; //紧邻的同级样式显示
}else {
cur.nextSibling.style.display="none";//紧邻的同级样式隐藏
}
}