事件:獲得焦點(diǎn)事件: onfocus JS引入外部文件 : script標(biāo)簽 需求分析在用戶提交表單的時候, 我們最好是能夠在用戶數(shù)據(jù)提交給服務(wù)器之前去做一次校驗(yàn),防止服務(wù)器壓力過大,并且需要給用戶一個友好提示 技術(shù)分析
步驟分析
代碼實(shí)現(xiàn)<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="css/style.css"/> <title></title> <!-- 1. 首先給必填項(xiàng),添加尾部添加一個小紅點(diǎn) 2. 獲取用戶輸入的信息,做相應(yīng)的校驗(yàn) 3. 事件: 獲得焦點(diǎn), 失去焦點(diǎn), 按鍵抬起 4. 表單提交的事件 Jq的方式來實(shí)現(xiàn): 1. 導(dǎo)入JQ的文件 2. 文檔加載事件: 在必填項(xiàng)后天加一個小紅點(diǎn) 3. 表單校驗(yàn)確定事件: blur focus keyup 4. 提交表單 submit --> <script type="text/javascript" src="js/jquery-1.11.0.js"></script> <script> $(function () {//默認(rèn)做一些頁面初始化 // 在所有必填項(xiàng)后天加一個小紅點(diǎn) * $(".bitian").after("<font class='high'>*</font>"); //給必填項(xiàng)綁定事件 $(".bitian").blur(function () { //首先獲取用戶當(dāng)前輸入的值 //var value = this.value; var value = $(this).val(); //清空當(dāng)前必填項(xiàng)后面的span //$(".formtips").remove(); $(this).parent().find(".formtips").remove(); //獲得當(dāng)前事件是誰的 if ($(this).is("#username")) { //判斷是否是用戶名輸入項(xiàng) //校驗(yàn)用戶名 if (value.length < 6) { $(this).parent().append("<span class='formtips onError'>用戶名太短了</span>"); } else { $(this).parent().append("<span class='formtips onSuccess'>用戶名夠用</span>"); } } if ($(this).is("#password")) {//判斷是否是密碼輸入項(xiàng) //校驗(yàn)密碼 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"); }); //$(".bitian").blur(function(){}).focus(function(){}).keyup(function(){}) //給表單綁定提交事件 $("form").submit(function () { //觸發(fā)必填項(xiàng)的校驗(yàn)邏輯 $(".bitian").trigger("focus"); //找到錯誤信息的個數(shù) var length = $(".onError").length if (length > 0) { return false; } return true; }); }); </script> </head> <body> <form action="index.html"> <div> 用戶名:<input type="text" class="bitian" id="username"/> </div> <div> 密碼:<input type="password" class="bitian" id="password"/> </div> <div> 手機(jī)號:<input type="tel"/> </div> <div> <input type="submit"/> </div> </form> </body> </html> |
|