检测鼠标中键点击事件jQuery

Cha*_*hak 9 jquery click mouseevent

当用户点击鼠标左键或中间的鼠标按钮时,我想将jQuery-UI对话框显示为弹出窗口.它适用于左键单击(我得到警告框,然后弹出窗口),但不适用于中间(既没有警报框也没有弹出窗口).我错过了什么?

$('a.external').live('click', function(e){
  if( e.which <= 2 ) {
    e.preventDefault();
    alert ("inside if");
  }
  popUp.start(this);
});
Run Code Online (Sandbox Code Playgroud)

nnn*_*nnn 20

使用mousedownmouseup代替click.并且(除非您使用的是非常旧版本的jQuery)使用.on()而不是.live():

$(document).on("mousedown", "a.external", function(e) {
   if( e.which <= 2 ) {
      e.preventDefault();
      alert ("inside if");
   }
   popUp.start(this);
});
Run Code Online (Sandbox Code Playgroud)

...理想情况下,你使用的父元素比链接更接近document.

演示:http://jsfiddle.net/7S2SQ/

  • @Nate - 我没有传递`"a.external"作为数据,_is_是委托事件的选择器.看看[`.on()`文档](http://api.jquery.com/on/).在这种情况下,mousedown事件绑定到文档,但是当它发生时,jQuery会自动检查源元素是否与第二个参数中的选择器匹配(并且只有在匹配时才调用您的函数).理想情况下,您不会绑定到文档:正如我在答案中所提到的,理想情况下,您将使用更接近链接的父元素. (3认同)

Apa*_*che 5

为了使其在 Firefox (40.0.3) 中完全正常工作,我必须实现.on('mouseup', fn)如下:

$(selector).on('mouseup', function (e) {

    switch (e.which)
    {
        // Left Click.
        case 1:
            // By way of example, I've added Ctrl+Click Modifiers.
            if (e.ctrlKey) {
                // Ctrl+LeftClick behaviour.
            } else {
                // Standard LeftClick behaviour.
            }
            break;

        // Middle click.
        case 2:
            // Interrupts "Firefox Open New Tab" behaviour.
            break;

        // Default behaviour for right click.
        case 3:
            return;
    }

    // Pass control back to default handler.
    return true;
});
Run Code Online (Sandbox Code Playgroud)