How to distinguish between left and right mouse click with jQuery

后端 未结 17 2685
独厮守ぢ
独厮守ぢ 2020-11-21 22:36

How do you obtain the clicked mouse button using jQuery?

$(\'div\').bind(\'click\', function(){
    alert(\'clicked\');
});

this is trigger

17条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 23:02

    It seems to me that a slight adaptation of TheVillageIdiot's answer would be cleaner:

    $('#element').bind('click', function(e) {
      if (e.button == 2) {
        alert("Right click");
      }
      else {
        alert("Some other click");
      }
    }
    

    EDIT: JQuery provides an e.which attribute, returning 1, 2, 3 for left, middle, and right click respectively. So you could also use if (e.which == 3) { alert("right click"); }

    See also: answers to "Triggering onclick event using middle click"

提交回复
热议问题