假设标签与输入位于 DOM 层次结构的同一级别,并且它紧邻标记中的输入,您可以执行类似的操作。
首先,一些示例 HTML:
<html>
    <body>
        <form onsubmit="return validation()" action="submit.php" method="post">
            <label for="name">Name:</label>
            <input type="text" value="" id="name" />
            <label for="email">Email:</label>
            <input type="text" value="" id="email" />
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
如您所见,所有输入前面都有一个带有正确 for 属性的标签。
现在对于 Javascript,它将进入头脑:
<script type="text/javascript">
    function validation() {
        //So we have a validation function.
        //Let's first fetch the inputs.
        name = document.getElementById("name");
        email = document.getElementById("email");
        //The variable error will increment if there is a validation error.
        //This way, the form will not submit if an error is found.
        error = 0; 
        //Now for validation.
        if(name.value.length < 6) {
            //We've found an error, so increment the variable
            error++;
            //Now find the corresponding label.
            nameLabel = name.previousSibling;
            //If we found the label, add an error class to it.
            if(nameLabel && nameLabel.for = name.id) {
                nameLabel.className = "error";
            }
        }
        ///////////////////
        //Do the same with the email...
        ///////////////////
        //Now, if there are no errors, let the form submit.
        //If there are errors, prevent it from doing so.
        return (error == 0) ? true : false;
    }
</script>
现在只需添加一些 CSS:
<style type="text/css">
.error {
  background-color: red;
}
</style>
编辑——我猜你不想要这种解决方案,但如果你想让它在去服务器之前验证,你就去吧。:)