天天看點

javascript封裝(表單校驗)

先上圖:

javascript封裝(表單校驗)

産品的需求是點選框内輸入時不提示錯誤,等滑鼠離開時校驗錯誤,那我就這樣寫

//增加提示代碼
$.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),'請輸入遊戲賬号');
	});           

這樣就一個方法被調用