问题
How can I bind mutiple events to the same function. I want click and touchstart to do the same. And then I want a second function for mouseover. I would like to use this kind of setup:
$(document).on({
click: function (event) {
// I want this: click, touchstart: function (event) {
event.preventDefault();
// do something
},
mouseover: function (event) {
event.preventDefault();
// do something
}
}, '.link');
回答1:
You can combine the events in one .on()
with space:
$(document).on('click touchstart', function(e) {
// this will be called on click as well as touchstart
});
回答2:
There's no reason why you can't call an external function instead:
function myExternalFunction (event) {
// do stuff
}
$(document).on({
click: myExternalFunction,
mouseover: myExternalFunction
}, '.link');
回答3:
According to the .on() documentation (and confirmed via a quick look at the .on()
implementation) you could do this:
$(document).on({
"click touchstart" : function (event) {
event.preventDefault();
// do something
},
mouseover: function (event) {
event.preventDefault();
// do something
}
}, '.link');
Demo: http://jsfiddle.net/XzkTm/
来源:https://stackoverflow.com/questions/17425311/bind-multiple-events-to-same-function