开发者

how can I differentiate the if the click event was triggered using the mouse or the enter key jquery

I have an event handler for the click event on an anchor. The event is fired both by clicking on the anchor and by the enter key when the anchor has开发者_如何学JAVA the focus.

I wanted to know if the event was triggered by a click o by the enter key.

Thanks!


I updated @patrick's demo using a bind with mouseup and keyup. When I used click instead of mouseup my message returned that I clicked when I actually pressed enter, but just the first time.

 $('a').bind('mouseup keyup', function(e){
  var msg = '';
  if (e.which == 13) {
   msg = 'enter pressed';
  } else if (e.which == 1) {
   msg = 'clicked';
  }
  alert( e.which + ': ' + msg );
  return false;
 })

Using e.which you will find that 1 = left mouse button, 2 = middle and 3 = right (I believe these numbers are right). So you can include all 3 if you need to.


$(document).ready(function(e) {
  $("a").keypress(function(e){
    if (e.keyCode==13) {
      alert('Enter!');
    }
  }).mousedown(function(){
    alert('Clicked!');
  });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜