實例代碼:javascript
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
(function($){
//正則表達式驗證
$.regTest=function(opt){
var currOpt=$.extend({
reg:"^Hello World!$",
regCase:"i",
regGlobal:"g",
regMulti:"m",
regVal:"Hello World!",
debug:false
},opt);
var strAttr=currOpt["regCase"].toString();
strAttr+=currOpt["regGlobal"].toString();
strAttr+=currOpt["regMulti"].toString();
var strReg=currOpt["reg"].toString();
var strVal=currOpt["regVal"].toString();
var isDebug=currOpt["debug"];
var regObj=new RegExp(strReg,strAttr);
if(isDebug){
var strLine="\r\n";
var strMsg="Reg:"+strReg+strLine;
strMsg+="RegAttr:"+strAttr+strLine;
strMsg+="RegVal:"+strVal+strLine;
strMsg+="RegExp Object Info:"+strLine;
$.each(regObj,function(key,value){
strMsg+="Key:"+key.toString()+",Value:"+value+"."+strLine;
});
window.alert(strMsg);
}
return regObj.test(strVal);
};
//正則表達式驗證幫助
$.regTestHelper=function(){
var strLine="\r\n";
var strMsg="$.regTest Help:"+strLine;
var currOpt={
reg:"^Hello World!$",
regCase:"i",
regGlobal:"g",
regMulti:"m",
regVal:"Hello World!",
debug:false
};
strMsg+="Default Options:"+strLine;
$.each(currOpt,function(key,value){
strMsg+=key+":"+value+"."+strLine;
});
return strMsg;
};
//驗證是不是中文
$.isChinese=function(strVal){
var strReg="^[\u4E00-\u9FA5]{2,4}$";
return $.regTest({
reg:strReg,
regVal:strVal
});
};
//獲取空間的trim後的value
$.TrimVal=function(selector){
return $.trim($(selector.toString()).val());
};
//控件獲取焦點
$.focusInput=function(selector){
try{
$(selector.toString()).focus();
return true;
}
catch(e){
return false;
}
};
})(jQuery);
$(function(){
window.alert("Welcome to the world of jQuery!");
window.alert($.regTestHelper());
$("input#btnTest").click(function(){
var inputSele="#txtName";
var strName=$.TrimVal(inputSele);
if(!$.isChinese(strName)){
window.alert("請輸入兩個到四個之間的漢字!");
$.focusInput(inputSele);
}
});
});
</script>
</head>
<body>
<label>姓名:<input type="text" id="txtName" value=""/></label>
<br/>
<label><input type="button" id="btnTest" value="測試" /> </label>
</body>
</html>html