我正在编写简单的表单验证器。
为了动态验证表单,我计划使用eval函数。
正如您在javascript编码中看到的那样, var funcCall成为函数的名称,其参数为jquery selected dom。
但这会造成错误。 (未捕获的SyntaxError:意外的标识符)
我想知道的是,我应该只在eval()中使用String还是有更好的方法来做到这一点?
var Submit = {
validateFilters : ["Submit.emptyCheckFilter"], // This is validator filters
emptyCheckFilter : function(element)
//this is filter to validate if it's empty or not.
console.log("this has been called");
},
doValidate : function(form) {
var children = $(form).children();
var filters = Submit.validateFilters;
$.each(children, function(key, value) { // Loop over form element
for(var i = 0; i < filters.length; i++) {
//Here's error comes the value is not String. it's selected item by jQuery.
//Uncaught SyntaxError: Unexpected identifier <= This occurs.
var funcCall = filters[i] + "(" + value + ");";
// Call the filter
eval(funcCall);
}
return false;
});
},
...
}
答案 0 :(得分:2)
你不应该使用eval。直接使用函数实例而不是“名称”更简单,更简洁。
var Submit = {
validateFilters : [function(element) {
//this is filter to validate if it's empty or not.
console.log("this has been called");
}], // This is validator filters
doValidate : function(form) {
var children = $(form).children();
var filters = Submit.validateFilters;
$.each(children, function(key, value) { // Loop over form element
for(var i = 0; i < filters.length; i++) {
filters[i](value);
}
return false;
});
},
...
}
答案 1 :(得分:1)
当你可以使用函数指针时,你不应该使用eval:
function emptyCheckFilter(x){}
// array contains the functions, not just their names
var filters = [emptyCheckFilter];
for(var i = 0; i < filters.length; i++) {
// call the functions, without using eval
filters[i](value);
}
答案 2 :(得分:0)
正如你的问题“eval()中使用的参数应该是字符串吗?”;
<强>语法强>
的eval(字符串)
<强>参数强>
字符串
表示JavaScript表达式,语句或语句序列的字符串。表达式可以包括现有对象的变量和属性。
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval