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