I quite understand that event.preventDefault()
will prevent any default behavior triggered by an event on browser, but this definition is too broad for me , for example what are those event default behavior on browser? since it's quite common to find developers use event.preventDefault()
but I still don't understand what kind of behavior they're trying to prevent.
If you click on a link, such as to http://example.com
, your browser's default behavior will be to take you to http://example.com
.
If you preventDefault
in a click handler, the browser will no longer change your window location.
document.querySelector('.prevent-default').addEventListener('click', function (e) { e.preventDefault(); }, false);
<a href="http://example.com">Normal Example</a> <a class="prevent-default" href="http://example.com">Prevented Example</a>
Other examples include:
submit
has associated form submission mousedown
has associated text selection keydown
has associated input touchstart
may have associated scrolling/zooming behaviors. one quick example is click
event. Let's say you have a tag like
<a href="/my-sub-page.html" class='ajax-link'>
default behavior will be when you click this link it will take you to the /my-sub-page.html page. but if you want to avoid page refresh and instead you want to use ajax. then you will use
$('.ajax-link').on('click', function(event){
event.preventDefault();
$.ajax({
url : $(this).attr('href'),
success : function(response){
$('.my-content').html(response);
}
})
});
or another example can be form submits. Similar to above, you canprevent default behavior of form submission, and use ajax and get result from post request without loading the page.
There are many default browser actions:
mousedown
– starts the selection (move the mouse to select). click
on <a href="">
- open the page. click
on <input type="checkbox">
– checks/unchecks the input. submit
– clicking an <input type="submit">
or hitting Enter inside a form field causes this event to happen, and the browser submits the form after it. keydown
– pressing a key may lead to adding a character into a field, or other actions. contextmenu
– the event happens on a right-click, the action is to show the browser context menu. etc.The event.preventDefault() method stops the default action of an element from happening.
For example:
Use the event.isDefaultPrevented() method to check whether the preventDefault() method was called for the event.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.