ekc*_*one 0 jquery events event-handling jquery-selectors
So I know that we can have multiple event handlers on the .on() method
$(document).on({
'click': function (e) {
// function
},
'hover': function (e) {
// function
}
});
Run Code Online (Sandbox Code Playgroud)
but is there anyway we can add multiple selectors to each event handler?
like this:
$(document).on('click', '#foo, .foo', function () {
// function
});
Run Code Online (Sandbox Code Playgroud)
but with multiple .on() methods:
$(document).on({
'click', '#foo': function (e) {
// doesn't work :(
},
'hover', '.foo': function (e) {
// doesn't work :(
}
});
Run Code Online (Sandbox Code Playgroud)
Thanks in advance
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;
};
Run Code Online (Sandbox Code Playgroud)
...which you could use like this:
$(document).mixon({
"#foo": {
"click focus": function() {
// ...
}
},
".foo": {
click: function() {
// ...
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3478 次 |
| 最近记录: |