需求:失去焦点的时候判断input按钮中的值,如果账号或密码在6-12个字符之间通过,否则报错。
注意:html中的input标签行内调用function的时候,是先通过window调用的function,所以打印this等于打印window。
只有传递的this才指的是标签本身。
示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单位数的验证</title>
    <style>
        span{
            color: red;
        }
        .hide {
            display: none;
        }
        .show {
            display: block;
        }
        .wrong {
            border: 1px solid red;
        }
        .right {
            border: 1px solid #91B81D;
        }
    </style>
</head>
<body>
    账号:<input type="text" onblur="fn(this)"><span class="hide">用户名不符合格式</span><br>
    密码:<input type="text " onblur="fn(this)"><span class="hide">密码不符合格式</span>
</body>
</html>
<script>
    var sp = document.getElementsByTagName("span")[0];
    function fn(inp) {
        if(inp.value.length<6 || inp.value.length>12){
            inp.className = "wrong";
            sp.className = "show";
        }else{
            inp.className = "right";
            sp.className = "none";
        }
    }
</script>
Last modification:March 28, 2018
If you think my article is useful to you, please feel free to appreciate