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按钮时,它会自动运行myFunctionOfChoice数据logs......这正是我不想要的。我要求的是,只有当我点击按钮时才console应该这样做。我怎样才能做到这一点?logsubmitForm

任何帮助表示赞赏!

4

1 回答 1

3

It's because you are calling the function right away.

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

Instead you should be passing the function reference:

submitFunction: myFunctionOfChoice

Now, when the submit button is clicked, you plugin should invoke the submitFunction passing the form's data.

You can do something like the following to pass the form's data to your function:

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);
    });
于 2013-11-03T18:37:17.990 回答