Can't use jquery's click event handler to detect right click

柔情痞子 提交于 2019-12-08 22:10:42

问题


In trying to detect a right mouse click with jquery, I noticed that the click event handler doesn't seem to be fired off with a right mouse click, while the mousedown or mouseup event handler's do.

For example, after a right click on the test div, the following alerts 'testing!':

$('#test').mousedown(function(e) {
    alert('testing');
});

However, the following does not:

$('#test').click(function(e) {
    alert('testing!');
});

Does anyone know why?


回答1:


As this article puts it:

There are no click events for right button clicks in any browser.

So you're left with mousedown and mouseup in most browsers.




回答2:


When you mousedown, the even fired has event.which

Taken from here: How to distinguish between left and right mouse click with jQuery

$('#element').mousedown(function(event) {
    switch (event.which) {
        case 1:
            alert('Left mouse button pressed');
            break;
        case 2:
            alert('Middle mouse button pressed');
            break;
        case 3:
            alert('Right mouse button pressed');
            break;
        default:
            alert('You have a strange mouse');
    }
});

So instead of using .click(), use mousedown and check for the cases.




回答3:


Not sure which browser(s) you've tested with, but according to MSDN the onclick fires "when the user clicks the left mouse button". I.e., by definition it doesn't occur for right (or middle) clicks. Given that's on MSDN you can expect IE to behave that way regardless of what the other browsers do.

(Onclick also fires for certain non-mouse things, like changing certain form elements with the keyboard, etc.)

I know jQuery tries to normalise behaviour between browsers, but if the browser doesn't fire the event at all...

There is at least one jQuery plugin that I know of that implements right-click: http://abeautifulsite.net/blog/2008/05/jquery-right-click-plugin/ (I haven't used it, but it looks good except that it notes that Opera doesn't support it).




回答4:


I have also tried the following code to catch right mouse click for certain class of elements

$(".brick").mousedown(function (event) {
            if (event.which === 3) {
                currentRightClickedTileID = $(this).attr("id");
            }
        });

This code doesn't always catch the right click.



来源:https://stackoverflow.com/questions/7343117/cant-use-jquerys-click-event-handler-to-detect-right-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!