I'd like to use jQuery to perform one single operation when one of the events happen, rather how to optimize this code:

$("#selector").on('click', function(){
 alert(1);
});

$("#selector").on('hover', function(){
 alert(1);
});

$("#selector").on('blur', function(){
 alert(1);
});

You see where I'm going with this. Basically it's one same functions but it's only the different triggers. Is there any way to stop me being redundant and wrap all this more simple?

有帮助吗?

解决方案

With multiple selector chaining

$('#element').on('click hover blur', function() {
    ...
});

You can also select multiple classes:

$('#foo, #bar, #element').on('click hover blur', function() {
    ...
});

其他提示

$('#element').on('click hover blur', function() {
    ...
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top