JS面向对象封装,判空判重
最近看网课,学了一点JS,面向对象。感谢杜老师!
egvo.js
1 //定义表单项类型 2 FormItem=function(lable,id){ 3 this.lable=lable; 4 this.id=id; 5 } 6 //工具类 7 EGOV=function(){ 8 //验证非空 9 this.isNotEmpty=function(formItemArr){ 10 for(var i=0;i<formItemArr.length;i++){ 11 var formItem=formItemArr[i]; 12 var id=formItem.id; 13 var lable=formItem.lable; 14 var domObj=document.getElementById(id); 15 if(domObj.value == ""){ 16 alert(lable+"不能为空,请填写"); 17 domObj.focus(); 18 return false; 19 20 } 21 } 22 return true; 23 } 24 //验证一致性(程序运行的时候formItem1和fornItem2都是FormItem类型的对象) 25 this.isSame=function(formItem1,FormItem){ 26 var id1=formItem1.id; 27 var lable1=formItem1.label; 28 var domobj1=document.getElementById(id1); 29 30 var id2=formItem2.id; 31 var lable2=formItem2.label; 32 var domobj2=document.getElementById(id2); 33 34 if(domobj1.value !=domobj2.value){ 35 alert(lable1 + "和" +lable2 +"不一致,请重新填写"); 36 domobj1.value=""; 37 domobj2.value=""; 38 domobj1.focus(); 39 return false; 40 } 41 return false; 42 } 43 } 44 45 var $=new EGOV();
引用的时候:
<script src="js/egov.js"></script> <script> function doUpdate(){ var ok=validataForm(); if(ok){ document.forms["userForm"].submit(); } } function validataForm(){ var formItem1=new FormItem("用户姓名","username"); var formItem2=new FormItem("用户密码","userpswd"); var formItem3=new FormItem("用户类型","orgtype"); var formItemArr=[formItem1,formItem2,formItem3]; return $.isNotEmpty(formItemArr); } </script>
搭上这一生命的列车,感受这生命的起点与终点