先上图:
产品的需求是点击框内输入时不提示错误,等鼠标离开时校验错误,那我就这样写
//增加提示代码
$.prototype.accounterror=function(info){
$(this).next("span").remove();
$(this).after("<span class='error'>"+info+"</span>");
}
$.prototype.accountok=function(info){
$(this).next("span").remove();
$(this).after("<span class='ok'>"+info+"</span>");
}
//检验账号
function checkAccount(){
var c=$("[name=account]");
if(c.val()==''){
c.accounterror('请输入游戏账号');
return false;
}else{
c.accountok('');
return true;
}
}
//鼠标事件
$("[name=account]").blur(function(){
checkAccount();
});
但是这就得思考一个问题,如果有很多需要检验的表单元素,那每个都重新写,很麻烦,性能也会变差,封装则可以解决这个问题
//封装检验
function Check(name,tips){
if(name.val()==''){
name.goodserror(tips);
return false;
}else{
name.goodsok('');
return true;
}
}
//鼠标响应
$("[name=account]").blur(function(){
Check($(this),'请输入游戏账号');
});
这样就一个方法被调用