是否有一种方法可以让按键、按键、模糊和更改事件在一行中调用相同的函数,或者我必须分别执行它们?

我的问题是,我需要验证一些数据与数据库查找,并希望确保验证不错过在任何情况下,无论是键入或粘贴到框。


当前回答

可以使用bind方法将函数附加到多个事件。只需要传递事件名称和处理函数,如下所示:

$('#foo').bind('mouseenter mouseleave', function() {
  $(this).toggleClass('entered');
});

另一个选择是使用jquery api的链接支持。

其他回答

而不是:

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

你可以使用:

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

输入触发键up键按模糊改变事件,甚至粘贴!

可以使用bind方法将函数附加到多个事件。只需要传递事件名称和处理函数,如下所示:

$('#foo').bind('mouseenter mouseleave', function() {
  $(this).toggleClass('entered');
});

另一个选择是使用jquery api的链接支持。

但为了防止多重触发:

var a;
var foo = function() {
    clearTimeout(a);
    a=setTimeout(function(){
        //your code
        console.log("Runned")
    },50);
}
$('textarea').on('blur change', foo);

你可以使用.on()将一个函数绑定到多个事件:

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

或者只是将函数作为参数传递给普通的事件函数:

var myFunction = function() {
   ...
}

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

是否有一种方法可以让按键、按键、模糊和更改事件在一行中调用相同的函数?

可以使用.on(),它接受以下结构:.on(events [, selector] [, data], handler),因此您可以将多个事件传递给该方法。在你的例子中,它应该是这样的:

$('#target').on('keyup keypress blur change', function(e) {
    // "e" is an event, you can detect the type of event using "e.type"
});

下面是一个活生生的例子:

$(" #目标”)。On ('keyup keypress blur change',函数(e) { console.log(' ' ${e.type.toUpperCase()}"事件发生') }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <输入id = "目标" >