开发者

Can I determine what event triggered an event handler in jQuery if I bind multiple ones?

开发者 https://www.devze.com 2023-01-12 21:25 出处:网络
Check this example: $(\'button\').bind(\'click focus\', function() { // Did I click or focus? }); Is there a way to work that out when binding multiple 开发者_运维百科events to one handler?

Check this example:

$('button').bind('click focus', function() {

   // Did I click or focus?
});

Is there a way to work that out when binding multiple 开发者_运维百科events to one handler?

This may work, but it is kind of ugly:

var eventType;

$('button').click(function() {
   eventType = 'click';
   do();
});

$('button').focus(function() {
   eventType = 'focus';
   do();
});

function do() {
    alert(eventType);
}


You can use event.type on the event object (the first param passed to the handler), like this:

$('button').bind('click focus', function(e) {
  if(e.type == "click") {
    //do something, it was a click
  }
});
0

精彩评论

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