多个事件正在发生什么行动

时间:2012-12-06 23:20:07

标签: javascript jquery

如果您拥有以下代码,请确定正在执行的操作或事件

$('#mydiv').on('click mousedown mousemove', function(event) { //<--multiple event
    if (action is mousedown) {

    }
    else if(action is mousemove){

    }
    else{
        //mouse click
    }
});

jsFiddle示例欢迎。

3 个答案:

答案 0 :(得分:3)

event.type会将事件类型设为字符串:

$('#mydiv').on('click mousedown mousemove', function(event) {
    switch(event.type) {
        case 'click':
                //do something on click
            break;
        case 'mousedown':
                //do something on mousedown
            break;
        case 'mousemove':
                //do something on mousemove 
            break;

       .....etc.
    }

});

您也可以这样做:

$('#mydiv').on(
   click: function() {
        //do something on click
   },
   mousedown: function() {
       //do something on mousedown
   },
   mousemove: function() {
      //do something on mousemove
   }
});

答案 1 :(得分:1)

您可以访问它所在的事件:

event.type

您的代码可以写成:

$('#mydiv').on('click mousedown mousemove', function(event) {
    if (event.type == 'mousedown') {

    }
    else if (event.type == 'mousemove'){

    }
    else{
        //mouse click
    }
});

参考:event.type

答案 2 :(得分:0)

您可以捕获event.type:

$('#mydiv').on('click mousedown mousemove', function(event) { //<--multiple event
    console.log(event.type);
});​

http://jsfiddle.net/ra9r5/