简体   繁体   中英

Why does return false work with alert but not console.log

I have a problem. With this html:

<div id="d"><div>Click me!</div><div>Or me</div></div>

When I use this code:

$("#d").on("mousedown", "div", function (e){
    console.log('clicked');
    if (e.which == 3) alert('left button clicked');
    return false;
});

It prevents the context menu from showing and alerts, but when I use this code:

$("#d").on("mousedown", "div", function (e){
    console.log('clicked');
    if (e.which == 3) console.log('left button clicked');
    return false;
});

It logs to the console, but doesn't prevent the context menu. I'm confused.

Here's a JSFiddle demonstrating the problem.

Oh, and please be patient if you happen to find a duplicate or something. I did try to find it.

You're not preventing the context menu with the first code. SOme browsers just don't open it anymore because of the alert window getting the focus. It's not the return false that prevents the menu, it's the alert itself.

I added an updated fiddle: http://jsfiddle.net/2D32L/12/

$("#f").on("contextmenu", "div", function (e) {
    e.preventDefault();
});

See this question for more information.

For the rest I agree with Johannes H. ; it's not the return value that cancels the contextmenu, it's the alert that does.

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