on()
是一种将 jQuery 的大部分事件绑定功能合并为一个的尝试。这还有一个额外的好处,就是可以解决效率低下的问题live
vs delegate
。在 jQuery 的未来版本中,这些方法将被删除并且仅on
and 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);
在内部,jQuery 地图all这些方法and简写事件处理程序设置器on()
方法,进一步表明你应该从现在开始忽略这些方法,只使用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 );
},
See https://github.com/jquery/jquery/blob/1.7/src/event.js#L965 https://github.com/jquery/jquery/blob/1.7/src/event.js#L965.