jquery combine event functions

2020-02-23 06:49发布

问题:

instead of example:

$(".myfield").blur(function() {
    // validate
})
$(".myfield").keyup(function() {
    // validate
})

is there a way to combine these two?

回答1:

Yes

$(".myfield").bind('blur keyup', function(){
  // validate
});

Reference: .bind()



回答2:

In case you want to validate each for itself...

$('.myfield').live('blur keyup', function(event) {
  if (event.type == 'blur') {
    // validate on blur
  }
  if (event.type == 'keyup') {
    // validate on keyup
  }
});


回答3:

use with .on() Event

$(document).on("keyup blur", "#myfield", function(event)
    {       
    // your code        

    });