自 jQuery 1.7 起,
on
docs 函数被用于替代绑定事件的现有方法:
one
docs 是一个特殊情况,请按原样使用。
现有事件仍然存在,只是别名为 on
。如博客文章和live
文档中所述,自 jQuery 1.7 起,live
和 die
已被弃用。
on
事件有多种格式,但函数签名如下:
.on( events [, selector] [, data], handler )
绑定:
$(selector).bind(events, data, handler);
$(selector).on(events, null, data, handler);
来源:
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
}
Delegate:
$(selector).delegate(subselector, events, data, handler);
$(selector).on(events, subselector, data, handler);
Source:
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
}
现场直播:
$(selector).live(events, data, handler);
$(document).on(events, selector, data, handler);
源代码:
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
}
请注意,使用
this.context = document;
设置了
this.context
,如在
$(document).on(...)
中指定的那样。
.bind()
和.delegate()
被认为是被取代而不是被弃用。看起来他们对.live()
采取了更坚定的立场,因为文档中指出了它的缺点。 - akavlie