jQuery 多个事件触发同一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2534089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery multiple events to trigger the same function
提问by shaneburgess
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?
有没有办法让keyup
, keypress
, blur
, 和change
events 在一行中调用相同的函数,还是我必须单独执行它们?
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.
我遇到的问题是我需要使用数据库查找来验证一些数据,并希望确保在任何情况下都不会错过验证,无论是键入还是粘贴到框中。
回答by Tatu Ulmanen
You can use .on()
to bind a function to multiple events:
您可以使用.on()
将函数绑定到多个事件:
$('#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)
回答by lesyk
As of jQuery 1.7, the .on()
method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind()
method is used for attaching an event handler directly to elements.
从 jQuery 1.7 开始,该.on()
方法是将事件处理程序附加到文档的首选方法。对于早期版本,该.bind()
方法用于将事件处理程序直接附加到元素。
$(document).on('mouseover mouseout',".brand", function () {
$(".star").toggleClass("hovered");
})
回答by Alain Tiemblo
I was looking for a way to get the event type when jQuery listens for several events at once, and Google put me here.
我正在寻找一种在 jQuery 一次侦听多个事件时获取事件类型的方法,而 Google 将我放在这里。
So, for those interested, event.type
is my answer :
所以,对于那些有兴趣的人,event.type
我的答案是:
$('#element').on('keyup keypress blur change', function(event) {
alert(event.type); // keyup OR keypress OR blur OR change
});
More info in the jQuery doc.
jQuery 文档中的更多信息。
回答by Giorgi
You can use bind methodto attach function to several events. Just pass the event names and the handler function as in this code:
您可以使用bind 方法将函数附加到多个事件。只需像以下代码一样传递事件名称和处理程序函数:
$('#foo').bind('mouseenter mouseleave', function() {
$(this).toggleClass('entered');
});
Another option is to use chaining support of jquery api.
另一种选择是使用 jquery api 的链接支持。
回答by Dave Ward
If you attach the same event handler to several events, you often run into the issue of more than one of them firing at once (e.g. user presses tab after editing; keydown, change, and blur might all fire).
如果您将相同的事件处理程序附加到多个事件,您通常会遇到同时触发多个事件的问题(例如,用户在编辑后按下 Tab;按键、更改和模糊可能都触发)。
It sounds like what you actually want is something like this:
听起来你真正想要的是这样的:
$('#ValidatedInput').keydown(function(evt) {
// If enter is pressed
if (evt.keyCode === 13) {
evt.preventDefault();
// If changes have been made to the input's value,
// blur() will result in a change event being fired.
this.blur();
}
});
$('#ValidatedInput').change(function(evt) {
var valueToValidate = this.value;
// Your validation callback/logic here.
});
回答by Sajjad Ashraf
This is how i do it.
这就是我的做法。
$("input[name='title']").on({
"change keyup": function(e) {
var slug = $(this).val().split(" ").join("-").toLowerCase();
$("input[name='slug']").val(slug);
},
});
回答by Coder Of The Galaxy
You could define the function that you would like to reuse as below:
您可以定义要重用的函数,如下所示:
var foo = function() {...}
And later you can set however many event listeners you want on your object to trigger that function using on('event') leaving a space in between as shown below:
稍后您可以在对象上设置任意数量的事件侦听器以使用 on('event') 触发该函数,在它们之间留出一个空格,如下所示:
$('#selector').on('keyup keypress blur change paste cut', foo);
回答by Squazz
The answer by Tatu is how I would intuitively do it, but I have experienced some problems in Internet Explorer with this way of nesting/binding the events, even though it is done through the .on()
method.
Tatu 的答案是我将如何直观地做到这一点,但我在 Internet Explorer 中遇到了一些问题,这种嵌套/绑定事件的方式即使是通过该.on()
方法完成的。
I havn't been able to pinpoint exactly which versions of jQuery this is the problem with. But I sometimes see the problem in the following versions:
我无法准确指出这是哪个 jQuery 版本的问题。但我有时会在以下版本中看到问题:
- 2.0.2
- 1.10.1
- 1.6.4
- Mobile 1.3.0b1
- Mobile 1.4.2
- Mobile 1.2.0
- 2.0.2
- 1.10.1
- 1.6.4
- 移动版 1.3.0b1
- 移动版 1.4.2
- 移动版 1.2.0
My workaround have been to first define the function,
我的解决方法是首先定义函数,
function myFunction() {
...
}
and then handle the events individually
然后单独处理事件
// Call individually due to IE not handling binds properly
$(window).on("scroll", myFunction);
$(window).on("resize", myFunction);
This is not the prettiest solution, but it works for me, and I thought I would put it out there to help others that might stumble upon this issue
这不是最漂亮的解决方案,但它对我有用,我想我会把它放在那里来帮助可能偶然发现这个问题的其他人
回答by Guest
$("element").on("event1 event2 event..n", function() {
//execution
});
This tutorialis about handling multiple events.
本教程是关于处理多个事件。
回答by Commercial Suicide
Is there a way to have
keyup
,keypress
,blur
, andchange
events call the same function in one line?
有没有一种方法有
keyup
,keypress
,blur
,和change
事件调用同一个函数在同一行?
It's possible using .on()
, which accepts the following structure: .on( events [, selector ] [, data ], handler )
, so you can pass multiple events to this method. In your case it should look like this:
可以使用.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"
});
And here is the live example:
这是现场示例:
$('#target').on('keyup keypress blur change', function(e) {
console.log(`"${e.type.toUpperCase()}" event happened`)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="target">