最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why right click is not triggered with .click()? - Stack Overflow

programmeradmin3浏览0评论

This is a simple code :

HTML

<a id="link" href="#">Ciao</a>

jQuery

$('#link').click(function () {
    alert("ciao");
});

in fact, left/middle button is triggered (the alert is printed) but with Right Click? Why not? And how can I trigger it?

This is a simple code :

HTML

<a id="link" href="#">Ciao</a>

jQuery

$('#link').click(function () {
    alert("ciao");
});

in fact, left/middle button is triggered (the alert is printed) but with Right Click? Why not? And how can I trigger it?

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jan 9, 2012 at 16:33 markzzzmarkzzz 48k126 gold badges317 silver badges534 bronze badges 1
  • 1 Related: stackoverflow./questions/1646851/jquery-right-click-event – David Commented Jan 9, 2012 at 16:36
Add a ment  | 

5 Answers 5

Reset to default 9

Bind mousedown to handle left, middle and right clicks:

$('#link').mousedown(function(e) {
   alert("ciao");
});

You can use e.which to determinate which button has been clicked. 1: left, 2: middle and 3: right.

Here's the demo: http://jsfiddle/fPhDg/9/


You can stop the contextmenu from appearing like this:

$('#link').contextmenu(false);

Demo: http://jsfiddle/y4XDt/

You should use this very very carefully! It only makes sense in some very rare cases.

Use .contextmenu(...):

$('#link').contextmenu(function () {
    alert("ciao");
});

And if you want to catch both events, you could use the bind(...) function:

$('#link').bind('click contextmenu',function()
{
    alert("ciao");
});

http://jsfiddle/fPhDg/4/

You can subscribe to the click event and the contextmenu event like so:

$('#link').on('click contextmenu', function (e) {
  if (e.which === 3) {
    // Right mousebutton was clicked
    // 1 is left mousebutton
    // 2 is centre mousebutton
  }
});

try this...

$('#link').mousedown(function (event) {
    if(event.which === 1)
    alert("left click");
    if(event.which === 2)
    alert("center click");
    if(event.which === 3)
    alert("right clikc");
});

fiddle : http://jsfiddle/fPhDg/8/

you can capture right mouse click like this :

<head>
<script>
function whichButton(event)
{
if (event.button==2)
  {
  alert("You clicked the right mouse button!");
  }
else
  {
  alert("You clicked the left mouse button!");
  }
}
</script>
</head>

<body onmousedown="whichButton(event)">
<p>Click in the document. An alert box will alert which mouse button you clicked.</p>
</body>
发布评论

评论列表(0)

  1. 暂无评论