Difference between handling $(“form”).submit or an

2019-01-12 06:39发布

问题:

Say I have the following HTML:

<form>
    ...some form fields...
    <input type="submit" id="submitButton" value="Submit" />
</form>

And I have a javascript method validate that checks the form fields for various invalid scenarios, returning true if all is well or false if there's something wrong.

Is there any real difference in jQuery between doing this:

$("form").submit(function() {
    return validate();
});

...or doing this:

$("#submitButton").click(function(){
    return validate();
});

And are there any advantages/disadvantages between the two?

回答1:

The click callback is called only if the user actually click on the submit button. But there are cases in which you would submit the form automatically by javascript, in that case the click callback is not fired while the submit callback is. I would recommend to use always the submit for validation and intrinsic action of the form, while using the click callback for animation or other things related to the action of clicking on the button.



回答2:

Click events are triggered earlier, the submit event fires after the click event.

Submit:

  • Could be too late to block the event if some data is wrong (Minior and old Browsers)
  • Triggers also on submit command

Click:

  • Overwhelming Events, nearly everything is binded with click. Performance?
  • Does not trigger on submit command


回答3:

The advantage of the first method is that if your form is submit by several buttons or completing different actions, then placing the validation on the submit button alone means the form could be in an invalid state if submit via the other methods.

The best method is to place validation on form submission because then, no matter how the form is being submit (by button click, programmatically from elsewhere) the validation will still be fired.