admin管理员组文章数量:1240594
I have two events that I want to observe on an object,
input.blur(function(event) {
ajaxSubmit(this);
event.preventDefault();
});
form.submit(function(event) {
ajaxSubmit(this);
event.preventDefault();
});
But I feel like this isn't dry enough, can I bind two events to my object input
and execute my function ajaxSubmit()
if either fire?
What would be super cool is if you could do:
input.bind("blur", "submit", function(event) {
ajaxSubmit(this);
event.preventDefault();
});
I have two events that I want to observe on an object,
input.blur(function(event) {
ajaxSubmit(this);
event.preventDefault();
});
form.submit(function(event) {
ajaxSubmit(this);
event.preventDefault();
});
But I feel like this isn't dry enough, can I bind two events to my object input
and execute my function ajaxSubmit()
if either fire?
What would be super cool is if you could do:
input.bind("blur", "submit", function(event) {
ajaxSubmit(this);
event.preventDefault();
});
Share
Improve this question
asked Dec 15, 2009 at 4:20
JP SilvashyJP Silvashy
48.5k50 gold badges153 silver badges230 bronze badges
2
-
1
You speak of "an object", but your sample references two objects (
input
andform
). – Crescent Fresh Commented Dec 15, 2009 at 4:24 - yah... I didnt really make any sense there huh. but what if they were the same object? and the events made sense, like "hover" and "blur" or something? is there a simpler way to bind multiple events? – JP Silvashy Commented Dec 15, 2009 at 4:30
2 Answers
Reset to default 11You can use the on method
$("#yourinput").on("blur submit", functionname);
Can bine any number of events; separate them with a space.
Yes, just declare the function and then bind it to the events:
var ajaxCallback = function(event){
ajaxSubmit(this);
event.preventDefault();
};
input.blur(ajaxCallback);
form.submit(ajaxCallback);
Note about variable declaration:
As @cletus points out, the way I declare the function provides a variable that is private to whichever scope it is defined in. I always program this way to minimize polluting the global namespace. However, if you are not defining both this callback and binding it to the elements in the same block of code, you should define it this way:
function ajaxCallback(event){ ... }
That way it is available wherever you later bind it using the .blur
and .submit
methods.
本文标签: javascriptCombining two event handlersJQueryStack Overflow
版权声明:本文标题:javascript - Combining two event handlers, jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740063519a2222718.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论