Copy codeThe Code is as follows:
// Eval is the value in the calculated string [any js code can be put ].
// 1,
Var str1 = '12 + 3 ';
Eval (str1); // 15
// 2,
Var str2 = '[1, 2, 3]';
Eval (str2 [0]); // 1
// 3,
Eval ('alert ("abc") '); // pop up abc
// 4,
Var str = "function show () {alert ('Love you ');}";
Eval (str );
Show ();
// 5. eval ---> json string
1. If you enter an empty verification field for the above user name and email address verification, the traditional approach is
Copy codeThe Code is as follows:
Var flag = true;
If (document. getElementById ("txtName"). value = ""){
// Write error message
Flag = false;
}
If (document. getElementById ("txtEmail"). value = ""){
// Write error message
Flag = false;
}
Return flag
}
--> However, if there are many fields to be verified, and they are not elegant at all.
2. calm down and take a look at html
Copy codeThe Code is as follows:
Username: <input type = "text" id = "txtName" name = "name"/> <br/>
Email: <input type = "text" id = "txtEmail" name = "email" value = ""/> <br/>
<Input type = "button" value = "verify" onclick = "validateForm ()"/>
2.1 check the following code:
Copy codeThe Code is as follows:
Function validateForm (){
Var nameV = form1.name. value ()
Alert (nameV); // if we enter "short hair beauty" in the text box, it must be "short hair beauty"
// Continue
NameV = eval ('form1. name. value ()');
Alert (nameV); // It is also "short hair" 5}
3. Encapsulation
Copy codeThe Code is as follows:
Function FormField (fieldName, fieldDesc) {// encapsulate the attributes and descriptions of the modifier.
This. fieldName = fieldName;
This. fieldDesc = fieldDesc;
}
String. prototype. MyTrim = function () {// remove leading and trailing Spaces
Return this. replace (/^ \ s + | \ s + $/g ,'');
}
Function validateForm (){
Var oUl = document. getElementById ("ulError ");
OUl. innerHTML = "";
Var list = new Array
(
// In the future, you only need to add an object to the array to verify that it is null.
New FormField ("name", "User name "),
New FormField ("email", "email ")
);
Var flag = true;
For (var I = 0; I <list. length; I ++ ){
Var fv = eval ("form1." + list [I]. fieldName + ". value"); // execute the eval operation
If (fv = null |! Fv. MyTrim ()){
// Record error information
// Var liError = "<li>" + list [I]. fieldDesc + "cannot be blank </li> ";
// OUl. innerHTML + = liError;
Var liError = document. createElement ("li ");
LiError. innerHTML = list [I]. fieldDesc + "cannot be blank ";
OUl. appendChild (liError );
Flag = false;
}
}
}