JavaScript 基础,登录验证
1.<script></script>的三种用法:
a.放在<body>中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>练习</title> </head> <body> <p id="demo" align="center">北京时间</p> <script> document.getElementById('demo').innerHTML = Date() document.write(Date()) </script> </body> </html>

b.放在<head>中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>练习</title> <script> function fnLogin() { window.alert('通过点击按钮会出现弹框警告') } </script> </head> <body> <div> <button onclick="fnLogin()">弹框警告</button> </div> </body> </html>


c.放在外部JS文件中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>练习</title> <script src="../static/js/lin1.js"></script> </head> <body> <div> <button onclick="fnLogin()">弹框警告</button> </div> </body> </html>
function fnLogin() { window.alert('html中链接到外部js文件,类似于css') } // function fnLogin() 与 onclick="fnLogin()" // document.getElementById('demo') 与 id="demo"


2. 三种输出数据的方式:
- 使用 document.write() 方法将内容写到 HTML 文档中。
- 使用 window.alert() 弹出警告框。
- 使用 innerHTML 写入到 HTML 元素。
- 使用 "id" 属性来标识 HTML 元素。
- 使用 document.getElementById(id) 方法访问 HTML 元素。
- 用innerHTML 来获取或插入元素内容
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>练习</title> <script> function fnLogin() { window.alert('hello') } </script> </head> <body> <p id="demo" align="left">中国标准时间</p> <script> document.getElementById('demo').innerHTML = Date() document.write('信管一班') </script> <div> <button onclick="fnLogin()">弹框警告</button> </div> </body> </html>


3. 登录页面准备:
- 增加错误提示框。
- 写好HTML+CSS文件。
- 设置每个输入元素的id
4. 定义JavaScript 函数。
- 验证用户名6-20位
- 验证密码6-20位
5. onclick调用这个函数。
css文件:
#container{width: 400px} #header{background-color: coral} #content{background-color: aquamarine} #footer{background-color: coral}
js文件:
function fnLogin() { var uSer = document.getElementById("user") var pAss = document.getElementById("pass") if (uSer.value.length < 6 || uSer.value.length > 20) { window.alert('用户名为6-20位') } if (pAss.value.length < 6 || pAss.value.length > 20) { window.alert('密码为6-20位') } }
html文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>练习</title> <link rel="stylesheet" type="text/css" href="../static/css/lin1.css"> <script src="../static/js/lin1.js"></script> </head> <body> <div id="container"> <div id="header"><h2 align="center">请登录</h2></div> <div id="content"> <form> Username:<input type="text" name="user" id="user" placeholder="请输入用户名"> <br> Password:<input type="password" name="pass" id="pass" placeholder="请输入密码"> <br> <input type="radio" name="r1" id="r1" value="stu">student <input type="radio" name="r2" id="r2" value="tea">teacher <br> <input type="checkbox" name="c1" id="c1" value="">记住我 <br> <input type="button" value="login" onclick="fnLogin()"> <a href="">忘记密码?</a> </form> </div> <div id="footer"><p align="right">版权@mis15</p></div> </div> </body> </html>



浙公网安备 33010602011771号