jQuery 多个事件触发同一个函数 [英] jQuery multiple events to trigger the same function

查看:45
本文介绍了jQuery 多个事件触发同一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让 keyupkeypressblurchange 事件调用相同的函数一行还是我必须分开做?

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 validation is not missed in any case, whether it is typed or pasted into the box.

推荐答案

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

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)

这篇关于jQuery 多个事件触发同一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆