2013-11-03 32 views
2

我得到了form;

<div id="mainDiv"> 
     <form> 

     <input name="input1" /> 
     <input name="input2" /> 
     <input name="input3" /> 
     <input name="input4" /> 

    <button id="showForm">Show Form</button>  
    <button id="sendForm">Submit Form</button>  
     </form> 
     </did> 

這是我的jQuery插件。

(function(o){ 
    o.fn.validateInputs = function(options){ 

     var settings = $.extend({ 

     submitButton:'', 
     submitFunction : function(){ 

     return "" 
     },options); 

    $(settings.submitButton).on('click',function(){ 

//......run the FunctionOfChoiceHere! 
//...I tried. 
console.log(settings.submitFunction) // This logs an Empty Function 
}) 
    } 
    })(jQuery); 

和普通jQuery

$('#showForm').on('click',function(){ 

$('#mainDiv').fadeIn() 
    var form = $(this).closest('form'); 
    var formData =$(form).serialize(); 

    $('input',form).validateInputs({ 

    submitFunction :myFunctionOfChoice(formData), 
    submitButton:'#submitForm' 
    }) 

    }) 

現在myFunctionOfChoice

function myFunctionOfChoice(data){ 

console.log(data); 
} 

的問題是,當點擊showForm按鈕,這將自動運行myFunctionOfChoicelogs數據....這是正是我不想。我要求的是,只有當我點擊submitForm按鈕時,console應該log。我怎樣才能做到這一點?

任何幫助表示讚賞!

回答

3

這是因爲您正在調用該功能。

//this calls the myFunctionOfChoice directly 
submitFunction :myFunctionOfChoice(formData) 

相反,你應該傳遞函數參考:

submitFunction: myFunctionOfChoice 

現在,點擊提交按鈕時,您插件應該調用submitFunction傳遞表單數據。

你可以做一些類似下面的表單的數據傳遞給你的函數:

o.fn.validateInputs = function(options) { 
    var $form = $(options.form), 
     me = this; 

    //... 

    $(settings.submitButton).on('click',function() { 
     //the this value inside the handler will be the input and data will get passed 
     //along with the form as the second parameter 
     settings.submitFunction.call(me, $form.serialize(), $form); 
    }); 
+0

你會如何傳遞參數? –

+0

你能解釋一下「通過表單的數據」是什麼意思嗎?......這將如何完成?... thanx –

+0

@UniversalGrasp我相應地更新了答案。這種方法也比你最初嘗試實現的要好,因爲表單數據可能會在表單顯示和提交按鈕被按下之間發生變化。 – plalx