on()
是将jQuery的大多数事件绑定函数合并为一个函数的try .这还有一个额外的好处,那就是用live
比delegate
来整理效率低下的地方.在future 的jQuery版本中,这些方法将被删除,只剩下on
和one
.
例如:
// Using live()
$(".mySelector").live("click", fn);
// Equivalent `on` (there isn't an exact equivalent, but with good reason)
$(document).on("click", ".mySelector", fn);
// Using bind()
$(".mySelector").bind("click", fn);
// Equivalent `on`
$(".mySelector").on("click", fn);
// Using delegate()
$(document.body).delegate(".mySelector", "click", fn);
// Equivalent `on`
$(document.body).on("click", ".mySelector", fn);
Internally, jQuery maps all these methods and shorthand event handler setters to the on()
method, further indicating that you should ignore these methods from now on and just use on
:
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
见https://github.com/jquery/jquery/blob/1.7/src/event.js#L965.