这种方法有什么作用?

时间:2011-09-19 11:35:31

标签: javascript css forms

脚本:

window.onload = initForms;

function initForms() {
for (var i=0; i< document.forms.length; i++) {
    document.forms[i].onsubmit = function() {return validForm();}
}
}

function validForm() {
var allGood = true;
var allTags = document.getElementsByTagName("*");

for (var i=0; i<allTags.length; i++) {
    if (!validTag(allTags[i])) {
        allGood = false;
    }
}
return allGood;

function validTag(thisTag) {
    var outClass = "";
    var allClasses = thisTag.className.split(" ");

    for (var j=0; j<allClasses.length; j++) {
        outClass += validBasedOnClass(allClasses[j]) + " ";
    }

    thisTag.className = outClass;

    if (outClass.indexOf("invalid") > -1) {
        thisTag.focus();
        if (thisTag.nodeName == "INPUT") {
            thisTag.select();
        }
        return false;
    }
    return true;

    function validBasedOnClass(thisClass) {
        var classBack = "";

        switch(thisClass) {
            case "":
            case "invalid":
                break;
            case "reqd":
                if (allGood && thisTag.value == "") {
                    classBack = "invalid ";
                }
                classBack += thisClass;
                break;
            default:
                classBack += thisClass;
        }
        return classBack;
    }
}
}

此代码用于检查用户是否在HTML表单中输入了必填字段。如果用户离开必填字段,则字段将标记为颜色。

在上面的代码中function validTag(thisTag)是做什么的?标识符 无效 是什么?这不会在HTML文件中的任何位置声明。如果这是HTML文件:

<html>
<head>
<title>Car Picker</title>
<script type="text/javascript" src="script.js"></script>    
<link rel="stylesheet" href="script.css" />
</head>
<body>
<h2 align="center">Car Picker</h2>
<form action="#">
<p>
    <label for="emailAddr">Enter your email address:&nbsp;&nbsp;&nbsp;&nbsp;  <input id="emailAddr" type="text" size="30" class="reqd email" />
    </label></br />
    <label for="emailAddr2">Re-enter your email address:<input id="emailAddr2" type="text" size="30" class="reqd emailAddr" />
    </label>
</p>
<p><label for="color">Colors:
    <select id="color" class="reqd">
        <option value="" selected="selected">Choose a color</option>
        <option value="Red">Red</option>
        <option value="Green">Green</option>
        <option value="Blue">Blue</option>
    </select>
</label></p>
<p>Options:
    <label for="sunroof"><input type="checkbox" id="sunroof" value="Yes" />Sunroof (Two door only)</label>
    <label for="pWindows"><input type="checkbox" id="pWindows" value="Yes" />Power Windows</label>
</p>
<p><label for="DoorCt">Doors:&nbsp;&nbsp;
    <input type="radio" id="twoDoor" name="DoorCt" value="twoDoor" class="radio" />Two
    <input type="radio" id="fourDoor" name="DoorCt" value="fourDoor" class="radio" />Four
</label></p>
<p><input type="submit" value="Submit" />&nbsp;<input type="reset" /></p>
    </form>
    </body>
    </html>

css文件:

body {
color: #000;
background-color: #FFF;
}

input.invalid {
background-color: #FF9;
border: 2px red inset;
}

label.invalid {
color: #F00;
font-weight: bold;
}

select {
margin-left: 80px;
}

input {
margin-left: 30px;
}

input+select, input+input {
margin-left: 20px;
}

3 个答案:

答案 0 :(得分:1)

如果设置了reqd类,如果指定的控件为空,则validBasedOnClass函数返回类名invalid。在这种情况下,该类将添加到控件中。 如果添加了类invalid,控件也会获得焦点。

所以它基本上是一个表单验证器,可以确保在发布表单之前填充类reqd的所有输入。

但是你从哪里得到这个代码,如果你显然不知道它是做什么的?它似乎也是非结构化的代码。我不会用它。

答案 1 :(得分:1)

  • 在上面的代码中,validTag(thisTag)函数是做什么的?

validTag函数正在检查所有reqd标记是否有效(如果标记为空,则标记无效)。

  • 什么是无效的标识符?

无效不是标识符,它是validBasedOnClass函数中设置的类名(如果标记无效,则设置它)。 (设置它的行是:classBack = "invalid ";

答案 2 :(得分:1)

仔细阅读评论。

function validTag(thisTag) {
    var outClass = "";
    var allClasses = thisTag.className.split(" ");
    /* <Array> allClasses = a list of all separate class names of `thisTag`*/

    /* This loop walks through all elements of the `allClasses` array, and
     * calls the `validBasedOnClasses` function (defined below). The return
     * value of the function is added to `outClass`, together with a space " "*/
    for (var j=0; j<allClasses.length; j++) {
        outClass += validBasedOnClass(allClasses[j]) + " ";
    }
    /*The class attribute of the element is set to the string `outClass`*/
    thisTag.className = outClass;

    /*Can the string "invalid" be found in the `outClass` string? */
    if (outClass.indexOf("invalid") > -1) {
        thisTag.focus();/* Puts the user focus to the element*/
        if (thisTag.nodeName == "INPUT") {
            /* Selects everything in the input, so that the user can easily
             * overwrite the contents of the input field*/
            thisTag.select();
        }
        return false; /*Invalid, return FALSE*/
    }
    return true; /*Valid, return TRUE*/

    /* <function> validBasedOnClass - a function used above
     * This function accepts a parameter, which equals one of the class names
     *  of the element */
    function validBasedOnClass(thisClass) {
        var classBack = ""; /* <string> classBack. This string will be returned*/

        switch(thisClass) {
            case "": /* An empty class name - Nothing to check*/
            case "invalid": /* "invalid" - Remove this class, so that the 
                             * code can validate again (when the "reqd" class
                             * is encountered) */
                break;
            case "reqd": /* class name == "reqd" */

                /* <boolean> `allGood` is defined at the main function.
                 * This function will only mark the FIRST invalid input field
                 * as defined in this function, and the main function */
                if (allGood && thisTag.value == "") {
                    classBack = "invalid "; /*Return class "invalid"*/
                }
                classBack += thisClass;
                /* `classBack` now holds "invalid reqd" or "reqd" */
                break;
            default:
                classBack += thisClass; /* Unknown class, ignore it */
        }
        return classBack; //Return the (altered) class
    }
}

注意:allGood是主函数(validForm)中定义的变量:

function validForm() {
    var allGood = true;
    var allTags = document.getElementsByTagName("*");

    for (var i=0; i<allTags.length; i++) { /*Walks through all elements*/
        if (!validTag(allTags[i])){ /*Checks whether an element is invalid or not*/
            allGood = false;
            /* `allGood` = false, notifies <function> allTags that an invalid
             * element has already been detected. */
        }
    }
   return allGood;

   ... //function validTag below

您的代码将验证元素,并将焦点放在第一个无效的元素上。