문제

I've been looking at some code posted by someone and I can't make sense of why he used preventDefault.

var $windows = $('#tgx-window,#tgs-window,#tgm-window,#tgl-window'), $buttons = $('#tgx-button,#tgs-button,#tgm-button,#tgl-button');
$windows.hide();

$buttons.on('click', function(e) {
    var $id;
    e.preventDefault();
    $buttons.removeClass('closebutton');
    $id = $('#' + this.id.split('-')[0] + '-window');// Get window id
    $windows.slideUp();
    if(! $id.is(':visible') ) {
        $id.slideDown();
        $(this).addClass('closebutton');
    }
});

It seems to behave exactly the same with or without it. My best guess so far is that it's common practice to use preventDefault/return false in function bodies.

My question is why he used that method at all?

Oh, yeah. I'm new to JavaScript.

http://jsfiddle.net/62NPt/53/

도움이 되었습니까?

해결책

From the docs:

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

So if your button is an input submit button for example, the event.preventDefault() will prevent the default behaviour of your button and prevent your form from submitting and reload the page. This is normally helpful when you want to apply AJAX call.

다른 팁

If the button is of type submit and in case of anchor if you use preventDefault() the default action of the event will not be triggered.

If you dont want to stop default action of element then it does not make any difference.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top