当前位置:  开发笔记 > 编程语言 > 正文

jQuery .on() method with multiple event handlers & multiple selectors

如何解决《jQuery.on()methodwithmultipleeventhandlers&multipleselectors》经验,为你挑选了1个好方法。

So I know that we can have multiple event handlers on the .on() method

$(document).on({
    'click': function (e) {
       // function
    },
    'hover': function (e) {
       // function    
    }
});

but is there anyway we can add multiple selectors to each event handler?

like this:

$(document).on('click', '#foo, .foo', function () { 
     // function
});

but with multiple .on() methods:

$(document).on({
    'click', '#foo': function (e) {
       // doesn't work :(
    },
    'hover', '.foo': function (e) {
       // doesn't work :(    
    }
});

Thanks in advance



1> T.J. Crowder..:

If you want different matching elements on different events, you need to use different on calls. You can use a single on call to hook multiple events for the same elements, but you can't use a single on for a mix and match of events and selectors (nor is there any need to).


You could, of course, create your own function that does that. For instance, something vaguely like:

$.fn.mixon = function(events) {
    Object.keys(events).forEach(function(selector) {
        var entry = events[selector];
        Object.keys(entry).forEach(function(event) {
            this.on(event, selector, entry[event]);
        }, this);
    }, this);
    return this;
};

...which you could use like this:

$(document).mixon({
    "#foo": {
        "click focus": function() {
           // ...
        }
    },
    ".foo": {
        click: function() {
           // ...
        }
    }
});

推荐阅读
可爱的天使keven_464
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有