uJavaScript 使我们有能力创建动态页面。事件是可以被 JavaScript 侦测到的行为。
u网页中的每个元素都可以产生某些可以触发 JavaScript 函数的事件。比方说,我们可以在用户点击某按钮时产生一个 onClick 事件来触发某个函数。事件在 HTML 页面中定义。
常见的HTML事件
属性 |
当以下情况发生时,出现此事件 |
onload |
某个页面或图像被完成加载 |
onunload |
用户退出页面 |
onclick |
鼠标点击某个对象 |
ondblclick |
鼠标双击某个对象 |
onchange |
用户改变域的内容 |
onblur |
元素失去焦点 |
onfocus |
元素获得焦点 |
onmouseout |
鼠标从某元素移开 |
onmouseover |
鼠标被移到某元素之上 |
onselect |
文本被选定 |
onsubmit |
提交按钮被点击 |
<html>
<head>
<title>用户注册</title>
<script type="text/javascript">
function userNameValidate() {
var userName = document.getElementById("userName").value;
if (userName) {
document.getElementById("uNameMsg").innerHTML = '';
return true;
}
// alert("用户名不能为空!");
document.getElementById("userNameMsg").innerHTML = '<font color="red" >对不起用户名不能为空</font>';
return false;
}
function passwordValidate() {
var password = document.getElementById("password").value;
if (password) {
var pwdReg = /^\d{6,12}$/;
if (pwdReg.test(password)) {
document.getElementById("passwordMsg").innerHTML = '';
return true;
} else {
document.getElementById("passwordMsg").innerHTML = '<font color="red">对不起,您的格式有误 </font>';
return false;
}
} else {
document.getElementById("passwordMsg").innerHTML = '<font color="red">对不起,密码不能为空 </font>';
return false;
}
}
function pwdValidate() {
var password = document.getElementById("password").value;
var pwd = document.getElementById("pwd").value;
if (pwd) {
if (pwd === password) {
document.getElementById("pwdMsg").innerHTML = '';
return true;
} else {
document.getElementById("pwdMsg").innerHTML = '<font color="red">对不起,您的格式有误 </font>';
return false;
}
} else {
document.getElementById("pwdMsg").innerHTML = '<font color="red">对不起,密码不能为空 </font>';
return false;
}
}
function isEmail() {
var reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
var email = document.getElementById("email").value;
if (email) {
if (reg.test(email)) {
document.getElementById("emailMsg").innerHTML = '';
return true;
} else {
document.getElementById("emailMsg").innerHTML = '<font color="red">对不起,您的格式有误 </font>';
return false;
}
}
return true;
}
function judge() {
return userNameValidate() && passwordValidate() && pwdValidate() && isEmail();
}
</script>
</head>
<body>
<form action="http://www.jd.com" method="post" onsubmit="return judge()">
<table>
<tr>
<td>用户名</td>
<td>
<input type="text" name="userName" id="userName" onblur="userNameValidate()" />
<lable id="userNameMsg"></lable>
</td>
</tr>
<tr>
<td>密码</td>
<td>
<input type="password" name="password" id="password" onblur="passwordValidate()" />
<lable id="passwordMsg"></lable>
</td>
</tr>
<tr>
<td>确认密码</td>
<td>
<input type="password" name="pwd" id="pwd" onblur="pwdValidate()" />
<lable id="pwdMsg"></lable>
</td>
</tr>
<tr>
<td>邮箱</td>
<td>
<input type="text" name="email" id="email" onblur="isEmail()" />
<lable id="emailMsg"></lable>
</td>
</tr>
<tr>
<td>
<input type="submit" id="submitValue" />
</td>
</tr>
</table>
</form>
</body>
</html>