知道的越多,所不知道的越多。如果帶給你幫助,點贊支持一下。
JavaScript事件處理的例題
1、表單驗證
要求:用戶名不少於2位,並且用戶名第一個字符需爲字母!
密碼長度必須在6~15之間。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>表單簡單驗證</title>
</head>
<body>
<h1>用戶登錄</h1>
<form name="form1">
用戶賬號:<input type="text" name="name1" /><br />
用戶密碼:<input type="password" name="password"/><br />
<input type="button" value="驗證" onclick="paanduan()" />
</form>
<script type="text/javascript">
function paanduan(){
if(document.form1.name1.value.length==0){
alert("用戶名不能爲空");
return false;
}
if(document.form1.password.value.length==0){
alert("密碼不能爲空");
return false;
}
var s= form1.name1.value.substr(0,1);
if(!((s>="a"&&s<="z")||(s>="A"&&s<="Z"))){
alert("用戶名第一個字符需爲字母!");
form1.name1.focus();
return false;
}
if(!(document.form1.password.value.length>=6&&document.form1.password.value.length<=15)){
alert("密碼長度必須在6~15之間");
return false
}
alert("登錄成功");
}
</script>
</body>
</html>
2、驗證數字輸入
如果輸入的值 x 不是數字或者小於 1 或者大於 10,則提示;輸入錯誤,否則提示:輸入正確。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>驗證數字輸入</title>
</head>
<body>
<h1>JavaScript驗證數字輸入</h1>
<p>請輸入1到10之間的數字:</p>
<form name="form">
<input type="text" name="x" />
<input type="button" value="提交" onclick="come(form.x.value)" />
</form>
<script type="text/javascript">
function come(x){
if(isNaN(x)||x<1||x>10)
alert("輸入錯誤");
else
alert("輸入正確");
}
</script>
</body>
</html>
3、利用document對象的bgColor屬性改變背景色,添加鼠標懸停事件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>變色</title>
</head>
<body>
<h1>移過來我變色給你看看</h1>
<span onmouseover="show1()" onmouseout="back()">變紅色</span>|
<span onmouseover="show2()" onmouseout="back()">變藍色</span>|
<span onmouseover="show3()" onmouseout="back()">變黃色</span>
<script type="text/javascript">
function show1(){
document.bgColor="red";
}
function show2(){
document.bgColor="blue";
}
function show3(){
document.bgColor="yellow";
}
function back(){
document.bgColor="white";
}
</script>
</body>
</html>
4.附加題(選做)
實際網站開發過程中,很有可能遇到這樣的情況:客戶要求將一串長數字分位顯示,例如將“13630016”顯示爲“13,630,016”。在本練習中通過編寫一個自定義函數,將輸入的數字字符格式化爲分位顯示的字符串。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>轉換數字</title>
</head>
<body>
<h3>請輸入要轉換的長數字:</h3>
<form name="form">
<input type="text" name="num" /><br/>
<input type="submit" value="轉換" onclick="changeNum(form.num.value)" />
<input type="reset" value="重置" />
</form>
<script type="text/javascript">
function changeNum(num){
if(isNaN(num)||num==""){
alert("請輸入數字!")
}
else
alert(Number(num).toLocaleString());
}
</script>
</body>
</html>