eventlistener一体化?

时间:2012-12-02 11:49:56

标签: javascript jquery

$something.on('mousedown touchstart mousemove', function(e){
   // everything do something
   if('mousedown') // do something

   if('touchstart') // do something

   if('mousemove') // do something
});

有可能做那样的事吗?什么是正确的方法?

2 个答案:

答案 0 :(得分:2)

您可以switch使用event.type

$something.on("mousedown touchstart mousemove", function(e) {
    switch (e.type) {
        case "mousedown":
            // do something
            break;

        case "touchstart":
            // do something
            break;

        case "mousemove":
            // do something
    }
});

答案 1 :(得分:0)

另一种方法是使用内部方法创建一个处理函数来匹配事件:

$('div').on('mouseenter click', evtHandler)

function  evtHandler(evt, el) {
    var _self=this, $el=$(this);

    var handler = {
        click: function() {
            $el.text('Div was clicked on')
        },
        mouseenter: function() {
            $el.css('background','#EAEAEA')
        }
    };
    handler[evt.type]();
}

DEMO:http://jsfiddle.net/ufYKF/