jQuery高級

目錄

1、遍歷

1.1傳統遍歷

1.2、jQuery對象遍歷

1.3 Jquery全局函數each遍歷 (★)

對象.each(函數)調用和$.each(對象,函數)調用區別(全局each函數的好處)

2、jQuery常用事件

2.1 dom對象綁定事件

2.2 jQuery對象綁定事件

普通綁定一個事件

 jQuery同時綁定多個事件

2.3 jQuery對象解綁事件

2.4 事件練習

3.練習

3.1省市聯動

3.2 左右互選

4、validate表單校驗插件

4.1 自帶demo查看:

4.2 仿照demo,自己寫校驗

4.2.1 設置錯誤提示信息爲紅色

4.2.2 引入js文件

4.2.3默認校驗規則

4.2.4 簡單模板

4.2.5 自定義錯誤提示標籤(默認提示信息位置錯位時)

小Bug

4.2.6 自定義校驗規則


 

1、遍歷

1.1傳統遍歷

var options=document.getElementsByTagName("option");
for(var i=0;i<options.length;i++){
	//alert(options[i].value);//value也行 但是不建議用(可能有瀏覽器不支持吧)  標籤中間的文本建議用innerHtml
	alert(options[i].innerHTML);
}

練習UI:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<!--需求 獲取所有option選項文本-->
		<script type="text/javascript">
			/*傳統形式的遍歷*/
			window.οnlοad=function(){//頁面上面寫必須先加加載方法,等頁面下的元素都加載完成了再執行
				//dom對象獲取所有的option標籤
				var options=document.getElementsByTagName("option");
				for(var i=0;i<options.length;i++){
					//alert(options[i].value);//value也行 但是不建議用(可能有瀏覽器不支持吧)  標籤中間的文本建議用innerHtml
					alert(options[i].innerHTML);
				}
			}
			
		</script>
		
	</head>
	<body>
		<select>
			<option>北京</option>
			<option>上海</option>
			<option>廣州</option>
			<option>深圳</option>
		</select>
	</body>
</html>

 

1.2、jQuery對象遍歷

jQuery對象調用函數each
$("").each( 自己定義的函數 回調函數 )
回調函數 : 函數是自己定義的,但不是自己調用

回調函數2個參數:索引 被遍歷到的元素    (也可以不寫參數遍歷時直接寫this)

<script type="text/javascript">
	$(function(){
		//獲取所有option標籤
		var $option=$("option");//標籤選擇器
		//jQuery對象(本質數組) 調用函數each即可
		//$option.each(匿名函數,又稱回調函數,自己定義框架調用);   
		//each遍歷數組,遍歷一個元素調用一次我寫的匿名函數
		//匿名函數有兩個參數: 參數1:索引  參數2:遍歷到的元素
		$option.each(function(i,a){
			//alert($(a).html());
		});
		
		//或者不寫參數  直接寫this也行
		$option.each(function(){
			alert($(this).html());
		});
	});
</script>

練習UI:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="../js/jquery-1.11.0.min.js" ></script>
		<script type="text/javascript">
			$(function(){
				//獲取所有option標籤
				var $option=$("option");//標籤選擇器
				//jQuery對象(本質數組) 調用函數each即可
				//$option.each(匿名函數,又稱回調函數,自己定義框架調用);   
				//each遍歷數組,遍歷一個元素調用一次我寫的匿名函數
				//匿名函數有兩個參數: 參數1:索引  參數2:遍歷到的元素
				$option.each(function(i,a){
					//alert($(a).html());//注意jQuery元素是數組,遍歷出來的是dom對象
				});
				
				//或者不寫參數  直接寫this也行
				$option.each(function(){
					alert($(this).html());
				});
			});
		</script>
	</head>
	<body>
		<select>
			<option>北京</option>
			<option>上海</option>
			<option>廣州</option>
			<option>深圳</option>
		</select>
	</body>
</html>

 

 

1.3 Jquery全局函數each遍歷 ()

jQuery框架內置了一個全局函數,each
全局意味着不需要jQuery對象調用, 直接由$調用的

$.each(被遍歷對象,匿名函數);
注意全局each函數的2個參數,匿名函數和直接對象調用each遍歷中的匿名函數作用語法相同

相同:回調函數2個參數:索引 被遍歷到的元素    (也可以不寫參數遍歷時直接寫this)

$(function(){
	//獲取所有option標籤
	var $option=$("option");//標籤選擇器
	//$.each(被遍歷對象,匿名函數);
	//注意全局each函數的2個參數,匿名函數和直接對象調用each遍歷中的匿名函數作用語法相同
	$.each($option, function(i,a) {
		//alert($(a).html())
	});
	
	//省略參數直接寫this
	$.each($option, function() {
		alert($(this).text())
	});
});

練習UI:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="../js/jquery-1.11.0.min.js" ></script>
		<script type="text/javascript">
			$(function(){
				//獲取所有option標籤
				var $option=$("option");//標籤選擇器
				//$.each(被遍歷對象,匿名函數);
				//注意全局each函數的2個參數,匿名函數和直接對象調用each遍歷中的匿名函數作用語法相同
				$.each($option, function(i,a) {
					//alert($(a).html())
				});
				
				//省略參數直接寫this
				$.each($option, function() {
					alert($(this).text())
				});
			});
		</script>
	</head>
	<body>
		<select>
			<option>北京</option>
			<option>上海</option>
			<option>廣州</option>
			<option>深圳</option>
		</select>
	</body>
</html>

 

 

對象.each(函數)調用和$.each(對象,函數)調用區別(全局each函數的好處)

全局each函數
    $.each(被遍歷對象,匿名函數);
    被遍歷對象可以是jQuery對象也可以是dom對象

$xx.each(function(){})只能被jQuery對象調用(多一步對象轉換)

所以全局each寫法麻煩一點,但是獲取的是dom對象時稍微好一點

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="../js/jquery-1.11.0.min.js" ></script>
		<script type="text/javascript">
			$(function(){
				//獲取所有option標籤
				var option=document.getElementsByTagName("option");
				$.each(option, function(i,a) {//可以直接遍歷dom對象
					alert($(a).text());
				});
			});
		</script>
	</head>
	<body>
		<select>
			<option>北京</option>
			<option>上海</option>
			<option>廣州</option>
			<option>深圳</option>
		</select>
	</body>
</html>

建議以後使用1.3 Jquery全局函數each遍歷 (★) 

 

2、jQuery常用事件

jQuery事件名稱沒有on

常用事件:
    click 點擊事件
    blur 失去焦點
    change 內容改變
    keyup 鍵盤彈起
    mouseover 鼠標懸停
    mouseout 鼠標離開

小插曲:js事件: onkeydown接收所有按鍵     onkeypress只接收有效字母鍵(12 a b接受   shift、esc不接受)

 

2.1 dom對象綁定事件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			//等到頁面加載完成再執行  否則解釋到此行就執行
			window.οnlοad=function (){
				//獲取按鈕
				var btn=document.getElementById("btn");
				//dom對象的事件屬性
				btn.οnclick=function (){
					alert("點我幹啥?")
				}
			}
		</script>
	</head>
	<body>
		<input type="button" value="按鈕" id="btn"/>
	</body>
</html>

 

2.2 jQuery對象綁定事件

普通綁定一個事件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="../js/jquery-1.11.0.min.js" ></script>
		<script type="text/javascript">
			//等到頁面加載完成再執行  否則解釋到此行就執行
			$(function(){
				//jQuery對象直接調用click()函數 傳入一個匿名函數爲參數
				$("#btn").click(function(){
					alert("又點我幹啥?");
				})
			});
			
		</script>
	</head>
	<body>
		<input type="button" value="按鈕" id="btn"/>
	</body>
</html>

 jQuery同時綁定多個事件

  jQuery對象中bind函數,可以實現對一個事件源同時綁定多個事件
       bind函數,實現綁定事件

bind綁定多個事件 每種類型的事件處理函數不同
$(xx).bind({
    "事件類型1":function(){},
    "事件類型2":function(){}
});

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="../js/jquery-1.11.0.min.js" ></script>
		<script type="text/javascript">
			$(function(){
				//bind綁定一個click事件  綁定一個事件不會用bind函數的
				/*$("#btn").bind("click",function(){
					alert("又點我幹啥?");
				})*/
				
				/*bind綁定多個事件 每種類型的事件處理函數不同
				 * bind({
				 * 	"事件類型1":function(){},
				 * 	"事件類型2":function(){}
				 * });
				*/
				$("#btn").bind({
					"click":function(){
						alert("綁定了一個點擊事件!")
					},
					"mouseover":function(){
						alert("綁定了一個鼠標懸停事件!");
					}
				});
			});
			
		</script>
	</head>
	<body>
		<input type="button" value="按鈕" id="btn"/>
	</body>
</html>

2.3 jQuery對象解綁事件

$("#btn").unbind();//解除所有事件
$("#btn").unbind("click");//解除click事件
$("#btn").unbind("click mouseover")//解除多個事件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="../js/jquery-1.11.0.min.js" ></script>
		<script type="text/javascript">
			$(function(){
				//先綁定事件
				$("#btn").bind({
					"click":function(){
						alert("綁定了一個點擊事件!")
					},
					"mouseover":function(){
						alert("綁定了一個鼠標懸停事件!");
					}
				});
				
				$("#unbtn").click(function(){
					//解除按鈕btn的事件綁定
					//unbind()什麼參數也不傳遞,就表示解除所有事件
					//$("#btn").unbind();//解除id=btn按鈕所有事件
					
					//$("#btn").unbind("click");//解除click事件
					
					//解除多個事件
					$("#btn").unbind("click mouseover")//注意寫法 一個字符串內空格隔開
				});
			});
			
		</script>
	</head>
	<body>
		<input type="button" value="普通按鈕" id="btn"/><br />
		<input type="button" value="解除綁定" id="unbtn"/>
	</body>
</html>

2.4 事件練習

文本框輸入內,下面div內放大展示  keyUp也只對可打印字母字符有效

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="../js/jquery-3.3.1.min.js" ></script>
		<script type="text/javascript">
			$(function(){
				var text=$("#text");
				//文本框綁定鍵盤彈起事件
				text.keyup(function(){
					//取出文本框中的內容放到div中  並放大顯示
					$("#div").html(text.val()).css("font-size","30px").css("color","red");
				});
			});
		</script>
	</head>
	<body>
		<input type="text" id="text" />
		<div id="div"></div>
	</body>
</html>

 

3.練習

3.1省市聯動

<tr>
	<td align="right">所在地</td>
	<td colspan="3">
		<select id="provinceId" οnchange="selectCity(this.value)" style="width:150px">
			<option value="">----請-選-擇-省----</option>
			<option value="0">北京</option>
			<option value="1">吉林省</option>
			<option value="2">江蘇省</option>
		</select>
		<select id="cityId" style="width:150px">
			<option value="">----請-選-擇-市----</option>
		</select>
		
	</td>
</tr>

<script type="text/javascript">
	function selectCity(value){
		/**
		 *  value是傳遞的標籤option的value的屬性值
		 *  作爲索引使用,到二維數組中,找出對應市
		 *  遍歷一維數組
		 *  追加到標籤 select中
		 */
		var citys = [
		  ["海淀","昌平","朝陽"],["長春","吉林","延邊"],["南京","徐州","蘇州"]
		];
		
		var city=citys[value];
		var cityId=$("#cityId");
		//拼接字符串操作
		var s="<option value=''>----請-選-擇-市----</option>";//注意內部一定要單引號  其實value屬性完全可以省略
		$.each(city, function(i,name) {
			s+="<option value='"+name+"+'>"+name+"</option>"
		});
		cityId.html(s);
		
	}
</script>

練習UI:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>用戶註冊</title>
		<style type="text/css">
			.regist_bg{
				  background: url(../img/regist_bg.jpg) repeat-x ;
				  width: 100%;
				  height: 600px;
				  padding-top: 40px;			
			}
			.regist{
				  border: 7px solid #ccc;
				  width: 800px;
				  padding: 40px 0;
				  padding-left: 80px;
				  background-color: #fff;
				  margin-left: 25%;				
			}
			input[type="submit"]{
				background-image: url(../img/register.gif);
				width: 100px; 
				height: 35px;
				color: #fff;
				cursor: pointer;
			}
		</style>
		<script type="text/javascript" src="../js/jquery-3.3.1.min.js" ></script>
		<script type="text/javascript">
			function selectCity(value){
				/**
				 *  value是傳遞的標籤option的value的屬性值
				 *  作爲索引使用,到二維數組中,找出對應市
				 *  遍歷一維數組
				 *  追加到標籤 select中
				 */
				var citys = [
				  ["海淀","昌平","朝陽"],["長春","吉林","延邊"],["南京","徐州","蘇州"]
				];
				
				var city=citys[value];
				var cityId=$("#cityId");
				//拼接字符串操作
				var s="<option value=''>----請-選-擇-市----</option>";//注意內部一定要單引號  其實value屬性完全可以省略
				$.each(city, function(i,name) {
					s+="<option value='"+name+"+'>"+name+"</option>"
				});
				cityId.html(s);
				
			}
		</script>
		
	</head>
	<body>
		<div class="regist_bg">
			<div class="regist">
				<form action="../index.html" >
					<table  width="600" height="350px">
						<tr>
							<td colspan="3">
									<font color="#3164af">會員註冊</font> USER REGISTER
							</td>
						</tr>
						<tr>
							<td align="right">用戶名</td>
							<td colspan="2"><input id="loginnameId" type="text" name="loginname" size="60"/> </td>
						</tr>
						<tr>
							<td align="right">密碼</td>
							<td colspan="2"><input id="loginpwdId" type="password" name="loginpwd" size="60"/> </td>
						</tr>
						<tr>
							<td align="right">確認密碼</td>
							<td colspan="2"><input id="reloginpwdId" type="password" name="reloginpwd" size="60"/> </td>
						</tr>
						<tr>
							<td align="right">Email</td>
							<td colspan="2"><input id="emailId" type="text" name="email" size="60"/> </td>
						</tr>
						<tr>
							<td align="right">姓名</td>
							<td colspan="2"><input name="text" name="username" size="60"/> </td>
						</tr>
						<tr>
							<td align="right">性別</td>
							<td colspan="2">
								<input type="radio" name="gender" value="男" checked="checked" />男
								<input type="radio" name="gender" value="女" />女
							</td>
						</tr>
						<tr>
							<td align="right">出生日期</td>
							<td colspan="2"><input type="text" name="birthday" size="60"/> </td>
						</tr>
						<tr>
							<td align="right">所在地</td>
							<td colspan="3">
								<select id="provinceId" οnchange="selectCity(this.value)" style="width:150px">
									<option value="">----請-選-擇-省----</option>
									<option value="0">北京</option>
									<option value="1">吉林省</option>
									<option value="2">江蘇省</option>
								</select>
								<select id="cityId" style="width:150px">
									<option value="">----請-選-擇-市----</option>
								</select>
								
							</td>
						</tr>
						<tr>
							<td width="80" align="right">驗證碼</td>
							<td width="100"><input type="text" name="verifyCode" /> </td>
							<td><img src="../img/code.png" /> </td>
						</tr>
						<tr>
							<td></td>
							<td colspan="2">
								<input type="submit" value="註冊" /> 
							</td>
						</tr>
					</table>
				</form>
			</div>
		</div>
		
	</body>
</html>

 

3.2 左右互選

eclipse部署web項目中的左右互相移動

其實很簡單,就一個選擇器寫法和append方法

//左->右移動選中
$("#add").click(function(){
      //後代選擇器+表單選擇器:$("#first option:selected")
    $("#second").append($("#first option:selected"));
});

//左->右移動全部
$("#add_all").click(function(){
    $("#second").append($("#first option"));
});

//右->左 移動選中
$("#remove").click(function(){
      //後代選擇器+表單選擇器:$("#first option:selected")
    $("#first").append($("#second option:selected"));
});

//右->左 移動全部
$("#remove_all").click(function(){
    $("#first").append($("#second option"));
});

練習UI:  上面的css不用看,看底部的代碼+標籤即可

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>左右互選</title>
		<style type="text/css">
		
			body
			{
				font-family:Courier;;
				font-size: 12px;
				margin:0px 0px 0px 0px;
				overflow-x:no;
				overflow-y:no;
				background-color: #B8D3F4;
			}
			td
			{
				font-size:12px;
			}
			.default_input
			{
				border:1px solid #666666;
				height:18px;
				font-size:12px;
			}
			.default_input2
			{
				border:1px solid #666666;
				height:18px;
				font-size:12px;
			}
			.nowrite_input
			{
				border:1px solid #849EB5;
				height:18px;
				font-size:12px;
				background-color:#EBEAE7;
				color: #9E9A9E;
			}
			.default_list
			{
				font-size:12px;
			  border:1px solid #849EB5;
			}
			.default_textarea
			{
				font-size:12px;
				border:1px solid #849EB5;
			}
			
			.nowrite_textarea
			{
				border:1px solid #849EB5;
				font-size:12px;
				background-color:#EBEAE7;
				color: #9E9A9E;
			}
			
			.wordtd5 {
				font-size: 12px;
				text-align: center;
				vertical-align:top;
				padding-top: 6px;
				padding-right: 5px;
				padding-bottom: 3px;
				padding-left: 5px;
				background-color: #b8c4f4;
			}
			
			.wordtd {
				font-size: 12px;
				text-align: left;
				vertical-align:top;
				padding-top: 6px;
				padding-right: 5px;
				padding-bottom: 3px;
				padding-left: 5px;
				background-color: #b8c4f4;
			}
			.wordtd_1 {
				font-size: 12px;
				vertical-align:top;
				padding-top: 6px;
				padding-right: 5px;
				padding-bottom: 3px;
				padding-left: 5px;
				background-color: #516CD6;
				color:#fff;
			}
			.wordtd_2{
				font-size: 12px;
				text-align: right;
				vertical-align:top;
				padding-top: 6px;
				padding-right: 5px;
				padding-bottom: 3px;
				padding-left: 5px;
				background-color: #64BDF9;
			}
			.wordtd_3{
				font-size: 12px;
				text-align: right;
				vertical-align:top;
				padding-top: 6px;
				padding-right: 5px;
				padding-bottom: 3px;
				padding-left: 5px;
				background-color: #F1DD34;
			}
			.inputtd
			{
				font-size:12px;
				vertical-align:top;
				padding-top: 3px;
				padding-right: 3px;
				padding-bottom: 3px;
				padding-left: 3px;
			}
			.inputtd2
			{
				text-align: center;
				font-size:12px;
				vertical-align:top;
				padding-top: 3px;
				padding-right: 3px;
				padding-bottom: 3px;
				padding-left: 3px;
			}
			.tablebg
			{
				font-size:12px;
			}
			
			.tb{
				border-collapse: collapse;
				border: 1px outset #999999;
				background-color: #FFFFFF;
			}
			.td2{line-height:22px; text-align:center; background-color:#F6F6F6;}
			.td3{background-color:#B8D3F4; text-align:center; line-height:20px; width:160px;}
			.td4{background-color:#F6F6F6;line-height:20px;}
			.td5{border:#000000 solid;
			       border-right-width:0px;
				   border-left-width:0px;
				   border-top-width:0px;
				   border-bottom-width:1px;}
			
			.tb td{
			font-size: 12px;
			border: 2px groove #ffffff;
			}
			.noborder {
				border: none;
			}
			
			.button {
				border: 1px ridge #ffffff;
				line-height:18px;
				height: 20px;
				width: 45px;
				padding-top: 0px;
				background:#CBDAF7;
				color:#000000;
				font-size: 9pt;
			    font-family:Courier;;
			} 
			
			.textarea {
				font-family: Arial, Helvetica, sans-serif, "??";
				font-size: 9pt;
				color: #000000;
				border-bottom-width: 1px;
				border-top-style: none;
				border-right-style: none;
				border-bottom-style: solid;
				border-left-style: none;
				border-bottom-color: #000000;
				background-color:transparent;
				text-align: left
			}
		
		</style>
		<script type="text/javascript" src="../js/jquery-3.3.1.min.js" ></script>
		<script type="text/javascript">
			$(function(){
				//左->右移動選中
				$("#add").click(function(){
					  //後代選擇器+表單選擇器:$("#first option:selected")
					$("#second").append($("#first option:selected"));
				});
				
				//左->右移動全部
				$("#add_all").click(function(){
					$("#second").append($("#first option"));
				});
				
				//右->左 移動選中
				$("#remove").click(function(){
					  //後代選擇器+表單選擇器:$("#first option:selected")
					$("#first").append($("#second option:selected"));
				});
				
				//右->左 移動全部
				$("#remove_all").click(function(){
					$("#first").append($("#second option"));
				});
			});
		</script>
		
	</head>

	<body>
	
	<div style="border:1px dashed #E6E6E6;margin:150px 0px 0px 450px; width:450px; height:300px; background-color:#E6E6E6;">
	<table width="385" height="169" border="0" align="left" cellpadding="0" cellspacing="0" style="margin:15px 0px 0px 15px;">
	  <tr>
	    <td width="126">
	    	<!--★ multiple="multiple" 能同時選擇多個   size="10"  確定下拉選的長度-->
			<select name="first" size="10" multiple="multiple" class="td3" id="first">
			  <option value="選項1">選項1</option>
			  <option value="選項2">選項2</option>
			  <option value="選項3">選項3</option>
			  <option value="選項4">選項4</option>
			  <option value="選項5">選項5</option>
			  <option value="選項6">選項6</option>
			  <option value="選項7">選項7</option>
			  <option value="選項8">選項8</option>
			</select>    
		</td>
	    <td width="89" valign="middle" align="center">
	       <input name="add"  id="add" type="button" class="button" value="-->" /> 
	       <input name="add_all" id="add_all" type="button" class="button" value="==>" /> 
	       <input name="remove"  id="remove" type="button" class="button" value="&lt;--" />
		   <input name="remove_all" id="remove_all" type="button" class="button" value="&lt;==" />
	    </td>
	    <td width="127" align="left">
		  <select name="second" size="10" multiple="multiple" class="td3" id="second">
	         <option value="選項9">選項9</option>
	      </select>
		</td>
	  </tr>
	</table>
	</div>
	</body>
</html>

 

4、validate表單校驗插件

editplus看括號匹配很好,已經激活

4.1 自帶demo查看:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>jQuery validation plug-in - main demo</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
<script src="../lib/jquery.js" type="text/javascript"></script>
<script src="../jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">

$(function() {
	// validate signup form on keyup and submit
	$("#signupForm").validate({
		rules: {
			/*冒號前面是name屬性值
			  冒號右邊"#password" 肯定就是id值了
			*/
			firstname: "required",
			lastname: "required",
			username: {
				required: true,
				minlength: 2
			},
			password: {
				required: true,
				minlength: 5
			},
			confirm_password: {
				required: true,
				minlength: 5,
				equalTo: "#password"
			},
			email: {
				required: true,
				email: true
			},
			topic: {
				required: "#newsletter:checked",
				minlength: 2
			},
			agree: "required"
		},
		messages: {
			firstname: "Please enter your firstname",
			lastname: "Please enter your lastname",
			username: {
				required: "Please enter a username",
				minlength: "Your username must consist of at least 2 characters"
			},
			password: {
				required: "Please provide a password",
				minlength: "Your password must be at least 5 characters long"
			},
			confirm_password: {
				required: "Please provide a password",
				minlength: "Your password must be at least 5 characters long",
				equalTo: "Please enter the same password as above"
			},
			email: "Please enter a valid email address",
			agree: "Please accept our policy"
		}
	});

	// propose username by combining first- and lastname
});
</script>
<style type="text/css">
#commentForm { width: 500px; }
#commentForm label { width: 250px; }
#commentForm label.error, #commentForm input.submit { margin-left: 253px; }
#signupForm { width: 670px; }
#signupForm label.error {
	margin-left: 10px;
	width: auto;
	display: inline;
}
#newsletter_topics label.error {
	display: none;
	margin-left: 103px;
}
</style>
</head>
<body>

<div id="main">
<form class="cmxform" id="signupForm" method="get" action="">
	<fieldset>
		<legend>Validating a complete form</legend>
		<p>
			<label for="firstname">Firstname</label>
			<input id="firstname2" name="firstname" />
		</p>
		<p>
			<label for="lastname">Lastname</label>
			<input id="lastname" name="lastname" />
		</p>
		<p>
			<label for="username">Username</label>
			<input id="username" name="username" />
		</p>
		<p>
			<label for="password">Password</label>
			<input id="password" name="password" type="password" />
		</p>
		<p>
			<label for="confirm_password">Confirm password</label>
			<input id="confirm_password" name="confirm_password" type="password" />
		</p>
		<p>
			<label for="email">Email</label>
			<input id="email" name="email" type="email" />
		</p>
		<p>
			<label for="agree">Please agree to our policy</label>
			<input type="checkbox" class="checkbox" id="agree" name="agree" />
		</p>
		<p>
			<input class="submit" type="submit" value="Submit"/>
		</p>
	</fieldset>
</form>
</div>
</body>
</html>

4.2 仿照demo,自己寫校驗

 

4.2.1 設置錯誤提示信息爲紅色

紅色展示需要自己設置:  .error{color:red} 
後面就知道了,提示框爲: <label for="name" class="error" style="display: none;">xxx</label>

4.2.2 引入js文件

<script type="text/javascript" src="../js/jquery-3.3.1.min.js" ></script>
<script type="text/javascript" src="../js/jquery.validate.min.js" ></script>

引入兩個js即可,提示信息最好還是自己寫吧

注意validate依賴於jQuery,所以一定要先引入jQuery,再引入validate

4.2.3默認校驗規則

(1)required:true                必輸字段
(2)remote:"check.php"      使用ajax方法調用check.php驗證輸入值
(3)email:true                    必須輸入正確格式的電子郵件
(4)url:true                        必須輸入正確格式的網址
(5)date:true                      必須輸入正確格式的日期 日期校驗ie6出錯,慎用
(6)dateISO:true                必須輸入正確格式的日期(ISO),例如:2009-06-23,1998/01/22 只驗證格式,不驗證有效性
(7)number:true                 必須輸入合法的數字(負數,小數)
(8)digits:true                    必須輸入整數
(9)creditcard:                   必須輸入合法的信用卡號
(10)equalTo:"#field"          輸入值必須和#field相同
(11)accept:                       輸入擁有合法後綴名的字符串(上傳文件的後綴)
(12)maxlength:5               輸入長度最多是5的字符串(漢字算一個字符)
(13)minlength:10              輸入長度最小是10的字符串(漢字算一個字符)
(14)rangelength:[5,10]      輸入長度必須介於 5 和 10 之間的字符串")(漢字算一個字符 包含5和10)
(15)range:[5,10]               輸入值必須介於 5 和 10 之間
(16)max:5                        輸入值不能大於5
(17)min:10                       輸入值不能小於10

4.2.4 簡單模板

注意一步一步的寫法:    學會自己動手寫,這樣比較好DBug,否則總是粘貼改,很苦惱

<script type="text/javascript">
	$(function(){
		$("#empForm").validate({
			
		});
	});
</script>
<script type="text/javascript">
	$(function(){
		$("#empForm").validate({
			/*rules和messages左邊的都是標籤的name值  右邊"#psw"是id*/
			//表單驗證規則
			rules:{
				realname:"required",
				username:{
					required:true,
					rangelength:[5,8]
				}
			},
			//提示信息
			messages:{
				realname:"真實姓名不能爲空",
				username:{
					required:"登錄名不能爲空",
					rangelength:"登錄名長度5~8"
				}
			}
		});
	});
</script>

 

4.2.5 自定義錯誤提示標籤(默認提示信息位置錯位時)

當錯誤信息提示位置不當時,可以自定義錯誤信息提示位置,自己寫錯誤提示標籤

label標籤 默認隱藏  for="name值" class="error"

 

小Bug

對於日期:

火狐瀏覽器支持得更好: 

google支持得不好:

好在日期都是讓用戶選,就不存在此問題了

注意:jQuery-validate 一個規則出了問題(規則很嚴格,一個','都不能少),所有表單元素的驗證都掛了   所以自己寫,寫完一個調試一個

 

4.2.6 自定義校驗規則

身份證號乃中華人共和國獨有,jQuery-validate內部肯定沒有內置,需要自定義規則

標準語法規則, jQuery選擇符號$調用插件屬性validator
屬性調用插件函數 addMethod()
    addMethod函數參數:
            規則名  
            回調函數

格式:
    $.validator.addMethod(guizeName,function(value,element,param){});

千萬注意validator後面沒有()  否則一直報錯  this.init is not a function

rules:需要先校驗的規則寫在前面    (提示信息順序無所謂)

//不要寫到$(function(){})裏面去了  傻傻在函數內定義函數
/*身份證號規則得自定義*/      
/*"cart15" 規則名
 * 
 * 匿名函數也有3個參數:
 * value:     文本框輸入的值
 * element:    文本框標籤對象
 * param:    規則需要用到的參數  eg:range:[5,10] 5和10就是參數
 */
//15位身份證號規則
$.validator.addMethod("cart15",function(value,element,param){
    if(value.length==18) return true;
    //定義15位規則   老式身份證號有15位  此處僅僅爲了演示而簡單校驗下是否是15位數字
    var reg=/^[0-9]{15}$/;
    return reg.test(value);
});
//18位身份證號規則
$.validator.addMethod("cart18",function(value,element,param){
    if(value.length==15) return true;
    //定義18位規則   前17位數字 最後一位爲數字或X
    var reg=/^[0-9]{17}[0-9X]{1}$/;
    return reg.test(value);
});
//自定義身份證號長度規則   必須爲15或18
$.validator.addMethod("cartlength",function(value,element,param){
    if(value.length==15 || value.length==18) return true;
    else return false;
});


//身份證號 15或18數字 寫在前面的規則先驗證  提示信息位置順序就無所謂了
rules:{
    cart:{
        required:true,
        cartlength:true,
        cart15:true,
        cart18:true
    }
},
messages:{
    cart:{
        //提示信息位置順序就無所謂了
        required:"身份證號不能爲空",
        cart15:"15位數字",
        cart18:"18位數字,最後一位可以爲X",
        cartlength:"長度15位或18位"
    }
}

------------------------------

整個validate練習UI:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>我的jquery表單校驗頁面</title>
        
		<style type="text/css">
			p{text-align: center;font-size:24px;}
			table{margin: 0 auto;border: 0;}
			table tr{height:40px;border:0;}
			table tr td{padding:0 14px;border:1px solid #999}
			.error{color:red}
		</style>
		
    	<script type="text/javascript" src="../js/jquery-3.3.1.min.js" ></script>
        <script type="text/javascript" src="../js/jquery.validate.min.js" ></script>
        
        <script type="text/javascript">
        	
        	//不要寫到$(function(){})裏面去了  傻傻在函數內定義函數
        	/*身份證號規則得自定義*/      
			/*"cart15" 規則名
			 * 
			 * 匿名函數也有3個參數:
			 * value: 	文本框輸入的值
			 * element:	文本框標籤對象
			 * param:	規則需要用到的參數  eg:range:[5,10] 5和10就是參數
			 */
			//15位身份證號規則
			$.validator.addMethod("cart15",function(value,element,param){
				if(value.length==18) return true;
				//定義15位規則   老式身份證號有15位  此處僅僅爲了演示而簡單校驗下是否是15位數字
				var reg=/^[0-9]{15}$/;
				return reg.test(value);
			});
			//18位身份證號規則
        	$.validator.addMethod("cart18",function(value,element,param){
				if(value.length==15) return true;
				//定義18位規則   前17位數字 最後一位爲數字或X
				var reg=/^[0-9]{17}[0-9X]{1}$/;
				return reg.test(value);
			});
			//自定義身份證號長度規則   必須爲15或18
			$.validator.addMethod("cartlength",function(value,element,param){
				if(value.length==15 || value.length==18) return true;
				else return false;
			});
			
        	$(function(){
        		$("#empForm").validate({
        			/*rules和messages左邊的都是標籤的name值*/
        			//表單驗證規則
        			rules:{
        				//姓名必須填寫
        				realname:"required",
        				//登錄名必須填寫 且長度5~8
        				username:{
        					required:true,
        					rangelength:[5,8]
        				},
        				//密碼:非空,長度6-12,非中文
        				psw:{
        					required:true,
        					rangelength:[6,12]
        				},
        				//確認密碼:非空,必須和密碼框一致
        				repsw:{
        					required:true,
        					rangelength:[6,12],
        					equalTo:"#psw"
        				},
        				//性別:非空
        				gender:"required",
        				//年齡:必填 範圍26-50之間
        				age:{
        					required:true,
        					range:[26,50]
        				},
        				//學歷:必選
        				edu:"required",
        				//生日:必填,格式合法
        				birthday:{
        					required:true,
        					dateISO:true,
        					date:true
        				},
        				//愛好:至少選一個
        				checkbox1:"required",
        				//郵箱:必填,格式正確
        				email:{
        					required:true,
        					email:true
        				},
        				//身份證號 15或18數字 寫在前面的規則先驗證  提示信息位置順序就無所謂了
        				cart:{
        					required:true,
        					cartlength:true,
        					cart15:true,
        					cart18:true
        					
        				}
        				
        			},
        			//提示信息
        			messages:{
        				realname:"真實姓名不能爲空",
        				username:{
        					required:"登錄名不能爲空",
        					rangelength:"登錄名長度5~8"
        				},
        				psw:{
        					required:"密碼不能爲空",
        					rangelength:"密碼長度6-12"
        				},
        				repsw:{
        					required:"確認密碼不能爲空",
        					rangelength:"密碼長度6-12",
        					equalTo:"輸入不一致"
        				},
        				//下面自定義了提示label 所以提示信息以下面的label中間的爲準 
        				gender:"請選擇",
        				age:{
        					required:"年齡不能爲空",
        					range:"年齡範圍26-50"
        				},
        				edu:"請選擇學歷",
        				birthday:{
        					required:"請選擇出生日期",
        					dateISO:"日期格式錯誤",
        					date:"無效日期"
        				},
        				//同樣默認的提示又錯位了 用的自定義的提示label 提示信息在自定義label裏寫
        				checkbox1:"請至少選",
        				email:{
        					required:"請填寫郵箱地址",
        					email:"郵箱地址不合法"
        				},
        				cart:{
        					//提示信息位置順序就無所謂了
        					required:"身份證號不能爲空",
        					cart15:"15位數字",
        					cart18:"18位數字,最後一位可以爲X",
        					cartlength:"長度15位或18位"
        				}
        			}
        		});
        	});
        </script>
        
        
        
</head>
<body>
    <p>員工信息錄入</p>
	<form name="empForm" id="empForm" method="post" action="test.html">
		<table border=1>
			<tr>
				<td>真實姓名(不能爲空 ,沒有其他要求)</td>
				<td><input type="text" id="realname" name="realname" />
				</td>
			</tr>
			<tr>
				<td>登錄名(登錄名不能爲空,長度應該在5-8之間,可以包含中文字符(一個漢字算一個字符)):</td>
				<td><input type="text" id="username" name="username" /></td>
			</tr>
			 <tr> 
		      <td>密碼(不能爲空,長度6-12字符或數字,不能包含中文字符):</td>
		      <td><input type="password" id="psw"  name="psw" /></td>
		    </tr>
		    <tr> 
		      <td>重複密碼密碼(不能爲空,長度6-12字符或數字,不能包含中文字符):</td>
		      <td><input type="password" id="repsw" name="repsw" /></td>
		    </tr>
		    <tr>
				<td>性別(必選其一)</td>
				<td>
				    <input  type="radio" id="gender_male" value="m" name="gender"/>&nbsp;男&nbsp;&nbsp;
				    <input  type="radio" id="gender_female" value="f" name="gender"/>&nbsp;女
				    <!-- 
				    	當錯誤信息提示位置不當時,可以自定義錯誤信息提示位置,自己寫錯誤提示標籤
				    	錯誤信息,提示在這裏
				    	使用標籤 label
				    	屬性 for
				    -->
				    <label for="gender" class="error" style="display: none;">請輸入性別</label>
				</td>
			</tr>
			<tr>
				<td>年齡(必填26-50):</td>
				<td><input type="text" id="age" name="age" /></td>
			</tr>
			
		    <tr> 
		      <td>你的學歷:</td>
		      <td> <select name="edu" id="edu">
			          <option value="">-請選擇你的學歷-</option>
			          <option value="a">專科</option>
			          <option value="b">本科</option>
			          <option value="c">研究生</option>
			          <option value="e">碩士</option>
			          <option value="d">博士</option>
		          </select>
			  </td>
		    </tr>
			
			<tr> 
              <td>出生日期(1982/09/21):</td>
               <td><input type="text" id="birthday"  name="birthday" value="" /></td>
            </tr>
			
		   <tr> 
		      <td>興趣愛好:</td>
		      <td colspan="2"> 
			      <input type="checkbox" name="checkbox1" id="qq1"/>&nbsp;乒乓球 &nbsp;
		          <input type="checkbox" name="checkbox1" id="qq2" value="1" />&nbsp;羽毛球 &nbsp;
		          <input type="checkbox" name="checkbox1" id="qq3" value="2" />&nbsp;上網 &nbsp;
		          <input type="checkbox" name="checkbox1" id="qq4" value="3" />&nbsp;旅遊 &nbsp;
		          <input type="checkbox" name="checkbox1" id="qq5" value="4" />&nbsp;購物 &nbsp;
		          <label for="checkbox1" class="error" style="display: none;">請至少選擇一個愛好</label>
		          
			  </td>
		    </tr>
			 <tr> 
			      <td align="left">電子郵箱:</td>
			      <td><input type="text" id="email" name="email" /></td>
			  </tr>
			  <tr> 
			      <td align="left">身份證(15-18):</td>
			      <td><input type="text" id="cart" name="cart" /></td>
			  </tr>
			<tr>
				<td></td>
				<td><input type="submit"  name="firstname"  id="firstname" value="保存"></td>
			</tr>
		</table>

</form>
</body>
</html>

 

 

發佈了388 篇原創文章 · 獲贊 89 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章