JavaScript 通过字符串函数名,调用对应的函数
function regexp_eng_num(value) { return value.match(new RegExp("^[0-9A-Za-z]*$")); } function regexp_num(value) { return value.match(new RegExp("^[0-9]*$")); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 function chkForm(f){ 2 var chk_list = { 3 plan_code:{ 4 name:'计划代码', 5 nullable:false, 6 grep:'regexp_eng_num' 7 }, 8 plan_name:{ 9 name:'计划名称', 10 nullable:false, 11 grep:'' 12 }, 13 plan_monthlypay:{ 14 name:'计划月费', 15 nullable:true, 16 grep:'regexp_num' 17 } 18 }; 19 20 for(key in chk_list){ 21 if(f[key] == null){ 22 continue; 23 } 24 25 if( chk_list[key]["nullable"] == false ){ 26 if (isNull(f[key].value)){ 27 return chk_list[key]["name"] +"没有输入"; 28 } 29 } 30 31 if(chk_list[key]["grep"]){ 32 if( !eval( chk_list[key]["grep"] + "('" + f[key].value + "')" ) ){ 33 return chk_list[key]["name"] +"输入错误"; 34 } 35 } 36 } 37 38 return ""; 39 }
关键就是eval()函数,这个函数可以把一个字符串当作一个JavaScript表达式一样去执行~~