简体   繁体   English

将相同的事件处理代码附加到jquery中的多个事件

[英]attaching same event handling code to multiple events in jquery

i have an input element, and i want bind both change and keypress event with the input, but event handling code is same for both the events. 我有一个输入元素,我希望使用输入绑定change和keypress事件,但事件处理代码对于这两个事件都是相同的。 is there any short way of doing this instead of writing the same code twice. 是否有任何简短的方法,而不是两次编写相同的代码。 well, i could write a method, but wanted to see if there is any easier way of doing this 好吧,我可以写一个方法,但想知道是否有更简单的方法来做到这一点

$("#inpt").change(function(){
   some code
});

$("#inpt").keypress(function(){
   same code
});

is there any way i can bind both events? 有什么方法可以绑定这两个事件吗?

You can use the jQuery on method. 您可以使用jQuery方法。

$("#inpt").on( "change keypress", function () {
     code
});

You can save the function and bind it to both: 您可以保存该功能并将其绑定到两者:

var fn = function(){ /*some code*/ };
$("#inpt").change(fn).keypress(fn);

You can also use the 'live' event instead of the 'bind' one sugested. 你也可以使用'live'事件而不是sugested'bind'。 The 'live' event will cover even dynamic created elements. “现场”活动甚至将涵盖动态创建的元素。 (Deprecated on 1.7) (已弃用1.7)

Kaless1n and Matthew, to bind to multiple elements use the "Attribute Starts With Selector": Kaless1n和Matthew,绑定到多个元素使用“Attribute Starts With Selector”:

var fn = function() { /*some code*/ };

$('input[id^="foo_"]').click(fn).keyup(fn).keydown(fn);

That will bind to all 'input' elements where the 'id' starts with 'foo_'. 这将绑定到'id'以'foo_'开头的所有'input'元素。 You can change 'input' to any onther element and/or the 'id' with the 'name' attribute for example. 例如,您可以将'input'更改为任何onther元素和/或'id'更改为'name'属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM