开发者

JQuery : event.preventDefault()

In which condition we use J开发者_C百科Query : event.preventDefault(); .... where it will be used ?


When you want to prevent the default behaviour. For example when handling a form submit event, if you want to post with ajax and not have your page refresh, you would use event.preventDefault().

$('#myform').submit(function(ev) {
    ev.preventDefault();
    // ajax stuff...
});

Returning false from your function will usually have the same effect.


function() {
  return false;
}

// IS EQUAL TO

function(e) {
  e.preventDefault();
  e.stopPropagation();
}

one other very good example is href

<a href="http://www.sometest.com" class="justtest">
test</a>

the following code will show an alert and takes the user to its default behavior which is href and www.sometst.com

$('.justtest').submit(function(ev) {
    alert("a href click");
});

if i use event.preventDefault , it will just show the alert and stops its default behavior.it doesn't take the user to www.sometest.com

$('.justtest').submit(function(ev) {
    alert("a href click");
    event.preventDefault();// this is better 
    // return faslse// return false will kill all the events so try to use preventDefault
});

got it from SO only

Returning false from jQuery event handlers is equivalent to calling both, e.preventDefault and e.stopPropagation.

So the difference is that preventDefault will only prevent the default event action to occur, i.e. a page redirect on a link click, a form submission, etc. and return false will also stop the event flow.

see this also

http://css-tricks.com/return-false-and-prevent-default/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜