检测用户名和密码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        /*高亮通过类样式实现*/
        .light {
            background-color: #f00;
        }
    </style>
    <script>
        window.onload = function () {
            var txtName = document.getElementById('txtName');
            var btnLogin = document.getElementById('btnLogin');
            var txtPwd = document.getElementById('txtPwd');

            // 检测用户名和密码是否满足位数条件 不满足条件高亮显示
            btnLogin.onclick = function () {
                if (txtName.value.length < 3 || txtName.value.length > 6) {

                    // 设置类样式通过className实现
                    txtName.className = 'light';
                    // 不满足条件的时候也会向服务器发送请求,怎么解决?---在这加个return
                    return;
                } else {
            // 设置类属性样式为空 txtName.className
= ''; } if (txtPwd.value.length < 6 || txtPwd.value.length > 8) { txtPwd.className = 'light'; // 不满足条件的时候也会向服务器发送请求,怎么解决?---在这加个return return; } else { txtPwd.className = ''; } // 向服务器发送请求 console.log('执行登录'); } } </script> </head> <body> 用户名<input type="text" name="" id="txtName" placeholder="必填"> 密码<input type="password" name="" id="txtPwd" placeholder="必填"><br> <input type="button" value="登录" id="btnLogin"> </body> </html>
原文地址:https://www.cnblogs.com/ella-li/p/14541232.html