jQuery multiple events to trigger the same function

Is there a way to have keyup , keypress , blur , and change events call the same function in one line or do I have to do them separately?

The problem I have is that I need to validate some data with a db lookup and would like to make sure that there is no way that the validation is missed weather it is typed or pasted into the box.


You can use .on() to bind a function to multiple events:

$('#element').on('keyup keypress blur change', function(e) {
    // e.type is the type of event fired
});

Or just pass the function as the parameter to normal event functions:

var myFunction = function() {
   ...
}

$('#element')
    .keyup(myFunction)
    .keypress(myFunction)
    .blur(myFunction)
    .change(myFunction)

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements.

$(document).on('mouseover mouseout',".brand", function () {
  $(".star").toggleClass("hovered");
})

I was looking for a way to get the event type when jQuery listens for several events at once, and Google put me here.

So, for those interested, event.type is my answer :

$('#element').on('keyup keypress blur change', function(event) {
    alert(event.type); // keyup OR keypress OR blur OR change
});

More info in the jQuery doc.

链接地址: http://www.djcxy.com/p/2870.html

上一篇: 扩展方法与静态实用程序类

下一篇: jQuery多个事件触发相同的功能