优化Jquery代码

时间:2015-05-13 09:16:45

标签: jquery validation

我使用jquery智能向导脚本将表单转换为向导。

这非常有效,但验证代码看起来可以更简单。

这是他们提供的例子。这可以成为一个循环,所以我不必为我的5个步骤编写它吗?

function validateSteps(step){
  var isStepValid = true;
   if(step == 1){
    if(validateStep1() == false ){
      isStepValid = false; 
      $('#wizard').smartWizard('showMessage','Please correct the errors in step '+step+ ' and click next.');
      $('#wizard').smartWizard('setError',{stepnum:step,iserror:true});         
    }else{
      $('#wizard').smartWizard('hideMessage');
      $('#wizard').smartWizard('setError',{stepnum:step,iserror:false});
    }
}

    if(step == 3){
     if(validateStep3() == false ){
       isStepValid = false; 
       $('#wizard').smartWizard('showMessage','Please correct the errors in step '+step+ ' and click next.');
       $('#wizard').smartWizard('setError',{stepnum:step,iserror:true});         
     }else{
       $('#wizard').smartWizard('hideMessage');
       $('#wizard').smartWizard('setError',{stepnum:step,iserror:false});
     }
    }

    return isStepValid;
 }

由于

1 个答案:

答案 0 :(得分:1)

你可以这样做,

function validateSteps(){
        var isStepValid = true, step =1;
        for(step ;step <=5;step ++){
            if(window["validateStep"+step ]() == false ){
              isStepValid = false; 
              $('#wizard').smartWizard('showMessage','Please correct the errors in step '+step + ' and click next.');
              $('#wizard').smartWizard('setError',{stepnum:step ,iserror:true});         
            }else{
              $('#wizard').smartWizard('hideMessage');
              $('#wizard').smartWizard('setError',{stepnum:step ,iserror:false});
            }

        }
        return isStepValid;

    }

您只需要担心有一个名为validateStepX

的函数
相关问题