如何将相同的函数绑定到不同的jQuery事件?

时间:2022-07-31 23:56:30

I want to bind a function that enables a button to the events changeand keypress. Is there a better manner than this:

我想绑定一个函数,使按钮能够进行事件更改和按键。有没有比这更好的方式:

 $(':input').change(function () {
    onInputChange();
}).keypress(function () {
    onInputChange();
});

thank you.

谢谢。

3 个解决方案

#1


6  

$(':input').on('change keypress', onInputChange);

#2


3  

$(':input').on("change keypress", function () {
    onInputChange();
});

Also: you can avoid the anonymous function in your case and just do:

另外:你可以在你的情况下避免使用匿名函数,只需:

$(':input').on("change keypress", onInputChange);

#3


3  

I believe this should do the trick:

我相信这应该成功:

$(':input').on('change keypress', onInputChange);

Note that this code assumes onInputChange is either not worried about the this context or event variable, or it accounts for them. You may alternatively want to use the following:

请注意,此代码假定onInputChange要么不担心此上下文或事件变量,要么考虑它们。您也可以使用以下内容:

$(':input').on('change keypress', function () {
    onInputChange();
});

#1


6  

$(':input').on('change keypress', onInputChange);

#2


3  

$(':input').on("change keypress", function () {
    onInputChange();
});

Also: you can avoid the anonymous function in your case and just do:

另外:你可以在你的情况下避免使用匿名函数,只需:

$(':input').on("change keypress", onInputChange);

#3


3  

I believe this should do the trick:

我相信这应该成功:

$(':input').on('change keypress', onInputChange);

Note that this code assumes onInputChange is either not worried about the this context or event variable, or it accounts for them. You may alternatively want to use the following:

请注意,此代码假定onInputChange要么不担心此上下文或事件变量,要么考虑它们。您也可以使用以下内容:

$(':input').on('change keypress', function () {
    onInputChange();
});