简体   繁体   中英

Behavior of e.preventDefault();

I am learning jQuery and am looking to clarify what e.preventDefault() does. From what I have read it prevents the default behaviour of the event.

An example in my case would be that I have an anchor tag which rather than take me to a new page I want it to display a modal on my screen. So my jQuery looks like this

$(document).ready(function() {
$('#boxShow').click(function(e) {
    e.preventDefault();
    $("#light").fadeIn();
    $('#fade').fadeIn();
});

Is the preventDefault() enabling me to perform a different event?

Apologies if this is a stupid question

It's easy, it prevents the default event from happening. For example an <a> element normally opens a link on click. In order to override that you will need to use this function.

This is easier to read once you use event instead of the acronym e .

$('a').click(function(event){
    event.preventDefault();
});

With an anchor element, the "default event" is to read the href ( hypertext reference ) value, and form a HTTP Request to for this location. In short, it directs the user to the URL of href value.

Therefore preventDefault() will prevent the href property from calling a HTTP Request, and just run your code underneath. Ie the 2 fadeIn() methods.

As per documentation , e.preventDefault(); prevents the default action of the event to be triggered.

In case of an anchor/hyperlink for example it should prevent the link from redirecting to the specified location.

From the jquery site:

If this method is called, the default action of the event will not be triggered.

So in the case of the anchor tag, it'll not take the user to another url, leaving you open to do what you want in the click event.

ps it's not a stupid question :-)

e.preventDefault(); will prevent default behavior of the action in case anchor(a) it will prevent opening new url associated with anchor. in case of form it will prevent submitting of form. but e.preventDefault(); would not work in IE as I dont support it. You shoould use e.returnValue = false;

code:

if(e.preventDefault){
      e.preventDefault();

}
else{
    e.returnValue = false; 
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM