现代的jQuery(1.7以上)使用.on()结合事件处理程序:
// 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");
});
旧版本的jQuery使用下列方法中的一个。对于所有元素,您可以有一个.live()或.delegate()事件处理程序。然后用它来触发您的自定义事件,像这样:
$(document.body).delegate(":input", "keyup", function(e) {
if(e.which == 13)
$(this).trigger("enter");
});
不适合你可以做正是你所拥有的任何:input元素:
$("selector").bind("enter", function(){
//enter was pressed!
});