知道的越多,所不知道的越多。如果带给你帮助,点赞支持一下。
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>