七、案例:JQ完成表单校验

1. 知识点

  • trigger :触发事件本身和事件中的函数内容
  • triggerHandler:仅触发事件中函数的内容,并不触发事件本身
    e.g 在文本框的获得焦点事件中,通过调用trigger来调用该事件的时候会使文本框获得焦点,并执行函数内容,是用triggerHandler仅执行函数内容而不获得焦点。
  • $(this).val()获取JQ对象的值value
  • JQ对象.is(选择器);用来判断是否符合选择器
  • 链式调用(在返回值为JQ对象的时候可以使用)
    • e.g$("#username").blur(function(){}).focus(function(){}).keyup(function(){});
  • JQ对象.find("选择器");用来获取该JQ对象中的符合选择器的元素
  • 在定义class时,如果要定义多个class的话用空格隔开<span class="xxx yyy">
  • JQ对象.remove():移除该对象
  • $("form").submit(function(){return true;});当函数返回true的时候,表单才提交数据

2. trigger和triggerHandler的案例

<html>
	<head>
		<script src="../js/jquery-1.11.0.js"></script>
		<script>
			$(function(){
				$("#username").focus(function(){
					$("#div1").append("触发了<br/>");
				});
				$("#btn1").click(function(){
					$("#username").trigger("focus");
				});
				$("#btn2").click(function(){
					$("#username").triggerHandler("focus");
				});
			});
		</script>
	</head>
	<body>
		<input type="text" id="username"/>
		<input type="button" id="btn1"  value="trigger触发focus事件"/>
		<input type="button" id="btn2"  value="triggerHandler触发focus事件"/>
		<div id="div1"></div>
	</body>
</html>

3. 案例的步骤

  1. 给必填项添加尾部的小红点;
  2. 获得用户输入的信息,做相应的校验;
  3. 事件:获得焦点事件,失去焦点事件,按键抬起事件;
  4. 表单提交的事件

4. 实现

<html>
	<head>
		<link rel="stylesheet" type="text/css" href="../css/style.css"/>
		<script src="../js/jquery-1.11.0.js"></script>
		<script>
			$(function(){
				$(".bitian").parent().append("<span class='high'>*</span>");
				$(".bitian").blur(function(){
					var value = $(this).val();
					$(this).parent().find(".formtips").remove();
					if($(this).is("#user")){
						if(value.length<6){
							$(this).parent().append("<span class='formtips onError'>用户名太短。</span>");
						}else{
							$(this).parent().append("<span class='formtips onSuccess'>用户名合法。</span>");
						}
				 	}
					if($(this).is("#pswd")){
						if(value.length<3){
							$(this).parent().append("<span class='formtips onError'>密码太短。</span>");
						}else{
							$(this).parent().append("<span class='formtips onSuccess'>密码合法。</span>");
						}
					}
				}).focus(function(){
					$(this).triggerHandler("blur");
				}).keyup(function(){
					$(this).triggerHandler("blur");
				}); 
				$("form").submit(function(){
					$(".bitian").trigger("blur");
					if($(".onError").length>0){
						return false;
					}
					return true;
				});
			});
		</script>
	</head>
	<body>
		<form action="../index.html">
			<div>用户名:<input type="text" id="user" class="bitian"/></div>
			<div>密码:<input type="password" id="pswd" class="bitian"/></div>
			<input type="submit" value="提交"/>
		</form>
	</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值