2013-07-25 70 views
1

我正在寫一個jQuery插件來驗證表單。該插件工作得很好,但我希望能夠定義表單驗證後會發生什麼。所以我想能夠傳遞一個函數作爲參數。該函數將包含大量實際提交表單的內容。驗證成功時需要調用該參數。jQuery驗證插件 - 通過函數作爲參數

插件稱爲HTML文件中:

<script> 
    $(document).ready(function(){ 
    $('#cForm').shdValidate({ 
     success : formSubmit() 
    }); 
    }); 
</script> 

jQuery插件:

(function($) { 
    $.fn.shdValidate = function(options) { 

    //==== SETTINGS 
    var shdValidateSuccess = $.extend(options).success, 
     form = this; 

    //==== SUBMIT CLICK 
    this.children('input[type=submit]').click(function(){ 
     //variables 
     var shdRequired = $(form).children('.required'), 
      shdValid = 0; 

     //validated fields 
     $(shdRequired).each(function(){ 
     $(this).removeClass('shdValidateAlert'); 
     if ($(this).val() == '' || $(this).val() == $(this).attr('placeholder')){ $(this).addClass('shdValidateAlert'); } 
     else { shdValid += 1; } 
     }); 

     //outcome 
     if (shdValid == $(shdRequired).length) { 
     //THE SUCCESS PARAMETER NEEDS TO BE CALLED HERE SOMEHOW 
     } 
     return false; 
    }); 

    } 
}(jQuery)); 

正如你所看到的,我評論的參數需要在插件被稱爲地方。目前我無法得到這個工作。

回答

2

你需要做出兩個改變

$(document).ready(function(){ 
    $('#cForm').shdValidate({ 
     success : formSubmit 
    }); 
    }); 

而且

(function($) { 
    $.fn.shdValidate = function(options) { 

    //==== SETTINGS 
    var shdValidateSuccess = $.extend(options).success, 
     form = this; 

    //==== SUBMIT CLICK 
    this.children('input[type=submit]').click(function(){ 
     //variables 
     var shdRequired = $(form).children('.required'), 
      shdValid = 0; 

     //validated fields 
     $(shdRequired).each(function(){ 
     $(this).removeClass('shdValidateAlert'); 
     if ($(this).val() == '' || $(this).val() == $(this).attr('placeholder')){ $(this).addClass('shdValidateAlert'); } 
     else { shdValid += 1; } 
     }); 

     //outcome 
     if (shdValid == $(shdRequired).length) { 
     //THE SUCCESS PARAMETER NEEDS TO BE CALLED HERE SOMEHOW 
     if($.isFunction(shdValidateSuccess)){ 
      shdValidateSuccess(form); 
     } 
     } 
     return false; 
    }); 

    } 
}(jQuery)); 
+0

Aaawwww yeeeeaaah。像魅力一樣工作,歡呼哥們。在6分鐘內您的方式即將來臨。 – Coop