Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

javascript - event.preventDefault() vs. return false (no jQuery)

I wondered if event.preventDefault() and return false were the same.

I have done some tests, and it seems that

  • If the event handler is added using old model, for example

    elem.onclick = function(){
        return false;
    };
    

    Then, return false prevents default action, like event.preventDefault().

  • If the event handler is added using addEventListener, for example

    elem.addEventListener(
        'click',
        function(e){
            return false;
        },
        false
    );
    

    Then, return false doesn't prevent the default action.

Do all browsers behave like this?

Are there more differences between event.preventDefault() and return false?

Where I can find some documentation (I couldn't in MDN) about return false behaving like event.preventDefault() in some cases?


My question is only about plain javascript, not jQuery, so please don't mark it as a duplicate of event.preventDefault() vs. return false, even if both questions have almost the same title.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The W3C Document Object Model Events Specification in 1.3.1. Event registration interfaces states that handleEvent in the EventListener has no return value:

handleEvent This method is called whenever an event occurs of the type for which the EventListener interface was registered. [...] No Return Value

under 1.2.4. Event Cancelation the document also states that

Cancelation is accomplished by calling the Event's preventDefault method. If one or more EventListeners call preventDefault during any phase of event flow the default action will be canceled.

which should discourage you from using any effect that returning true / false could have in any browser and use event.preventDefault().

Update

The HTML5 spec actually specifies how to treat a return value different. Section 7.1.5.1 of the HTML Spec states that

If return value is a WebIDL boolean false value, then cancel the event.

for everything but the "mouseover" event.

Conclusion

I would still recommend to use event.preventDefault() in most projects since you will be compatible with the old spec and thus older browsers. Only if you only need to support cutting edge browsers, returning false to cancel is okay.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...