JQuery same function for multiple events (ex: hover and click event)
is there any way to execute same code开发者_StackOverflow社区 for different events on the page?
$('.class1').hover(function() {
some_function();
});
$('.class1').click(function() {
some_function();
});
instead to do something like:
$('.class1').click.hover(function() {
some_function();
});
Use bind():
$('.class1').bind("click hover", function() {
some_function();
});
While bind is the way to go if you want to attach the event handlers at the same point in your code using the same selector, if you want to attach them at different points or using different selectors, you could always just use a named function, rather than an anonymous one:
function someWrappingFunction() {
some_function();
}
$('.class1').hover(someWrappingFunction);
$('.class1, .anotherClass').click(someWrappingFunction);
精彩评论