How do I create a custom onEnter event in jQuery?
I would like to create a custom event in jQuery that captures ENTER onkeypress events, so that I would not have to code this way every time:
if(e.keyCode == 13) {
// event code here
}
In other words, I would like to be abl开发者_JAVA百科e to code like this:
$("selector").bind("enter", function(){
// event code here
});
Modern jQuery (1.7 and up) uses .on()
to bind event handlers:
// delegate binding - replaces .live() and .delegate()
$(document.body).on("keyup", ":input", function(e) {
if(e.which == 13)
$(this).trigger("enter");
});
// direct binding - analogous to .keyup()
$(":input").on("keyup", function(e) {
if(e.which == 13)
$(this).trigger("enter");
});
Older versions of jQuery use one of the following methods. You could have a single .live()
or .delegate()
event handler for all elements. Then use that to trigger your custom event, like this:
$(document.body).delegate(":input", "keyup", function(e) {
if(e.which == 13)
$(this).trigger("enter");
});
Not for any :input
element you could do exactly what you have:
$("selector").bind("enter", function(){
//enter was pressed!
});
You can test it out here.
$("selector").keyup(function (e) {
if (e.keyCode == 13) {
$(this).trigger("enter");
}
}).bind("enter", function () {
// event code here
});
It is a good idea to use namespaced event names, to reduce the chance of accidentally clashing with other jQuery code that uses custom events. So instead of "enter"
you could use "enter.mywebapp"
or something similar. The makes the more sense the more custom events you use.
精彩评论