jquery clarification regarding preventDefault
http://api.jquery.com/event.preventDefault/
"If this method is called, the default action of the event will not be triggered."
"default action" means redirecting people from a different page when they click a hyperlink, as far as i observed in sample code.
is there any other use for this func开发者_JAVA技巧tion?
how does it interact with forms?
As you said, preventDefault
prevents the default action of the event from being triggered. The default action of the event depends on the type of event, and the event target.
For example, if preventDefault
was used in a click event handler for a checkbox, the checkbox would not become checked upon click. If it was used in a keydown
event handler for an text input, the pressed key would not be written to the input value. If it was used in a submit
event handler for a form, it would prevent the form from submitting.
Basically, it stops any event from performing the action it would perform by default.
preventDefault
will prevent the default event occuring, so, for example, if we linked the following code to a form -
$('#form').submit(function(e) {
alert('Handler for .submit() called.');
e.preventDefault();
});
The e.preventDefault()
call will prevent the form being submitted as that is the default event that would normally occur on a form submit.
It prevents the default action of the element, whatever that default action might be.
In the case of forms and inputs, in response to a click or such, it would prevent checking a radio-button or checkbox, it would prevent the submission of the form (or whatever action was specified) when clicking the submit
button.
preventDefault()
prevents any default action of browser or so for the specified event.
There are many practical use of preventDefault()
, I have summarized a few for you. You will also find the answer to your question about forms within this.
It prevents:
- Submitting form while clicking submit button
- Submitting form while pressing enter
- Sometimes it can also prevent scrolling
- Keypress actions also.
- Right click browser menu
- Opening new tabs while clicking middle button on link
- Opening links while clicking left button, as you mentioned,
And there are many
精彩评论