Multiple jQuery events on one element with differe

2019-05-18 07:05发布

问题:

Is there a way to combine these two methods of handling the event attachment in jQuery?

$('selector').on({
    mouseenter: function() {},
    mouseleave: function() {},
    mousedown:  function() {},
    mouseup:    function() {}
});

I prefer the previous method but need something like the following to work with "live"-events (the problem is that this will not work if there's a comment between the handlers):

$(document).on('mouseenter', 'selector1', function(){})
           .on('mouseleave', 'selector2', function(){})
           .on('mousedown',  'selector3', function(){})
           .on('mouseup',    'selector4', function(){});

However, is there a workaround to do it like this?:

$(document).on({
    mouseenter: 'selector1': function() {},
    mouseleave: 'selector2': function() {},
    mousedown:  'selector3': function() {},
    mouseup:    'selector4': function() {}
});

Update

I've ended up with this simple on-wrapper function: https://gist.github.com/4191657

The usage is quite simple:

$(document).act(
    ['mouseenter', 'selector1', function() {}],
    ['mouseleave', 'selector2', function() {}],
    ['mousedown', 'selector3', function() {}],
    ['mouseup', 'selector4', function() {}]
);

Any suggestions or improvements to this?

回答1:

Look at the jQuery docs for the .on() method. You can pass a selector as the second argument when you use the event map version that you use in your first example:

$(document).on({
    mouseenter: function() {},
    mouseleave: function() {},
    mousedown: function() {},
    mouseup: function() {}
}, "selector");

This assumes that you want to use the same selector for all of those events. If it can differ, your best option may be to chain the calls to .on():

$(document).on('mouseenter', 'selector1', function(){})
           .on('mouseleave', 'selector2', function(){})
           // ...etc


回答2:

I've managed to improve your wrapper function so that it's possible to use objects instead of arrays when defining events. In similar way how Meteor.js does it.

// inspired by https://gist.github.com/yckart/4191657
// This code allows you to use more easy to read syntax to define events in jQuery
// Usage:
// $(document).events({
//  'click, .target-selector': function() {
//      //your function to trigger when target selector is clicked
//  }
// });

;(function($) {
    $.fn.events = function() {
        var argumentsObject = arguments[0];
        return this.each(function() {   
            for (var propertyName in argumentsObject) {
                if (argumentsObject.hasOwnProperty(propertyName)) {
                    var argumentsToPass = propertyName.split(", ");
                    argumentsToPass.push(argumentsObject[propertyName]);
                    $(this).on(argumentsToPass[0], argumentsToPass[1], argumentsToPass[2]);
                }
            }
        });
    };
})(jQuery);