在jQuery v1.7on中添加了一种新方法.从文档:
'.on()方法将事件处理程序附加到jQuery对象中当前选定的元素集.从jQuery 1.7开始,.on()方法提供了附加事件处理程序所需的所有功能.
什么是与差异live和bind?
And*_*y E 329
on()是尝试将大多数jQuery的事件绑定函数合并为一个.这有助于整理livevs 的低效率delegate.在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);
Run Code Online (Sandbox Code Playgroud)
// Using bind()
$(".mySelector").bind("click", fn);
// Equivalent `on`
$(".mySelector").on("click", fn);
Run Code Online (Sandbox Code Playgroud)
// Using delegate()
$(document.body).delegate(".mySelector", "click", fn);
// Equivalent `on`
$(document.body).on("click", ".mySelector", fn);
Run Code Online (Sandbox Code Playgroud)
在内部,jQuery将所有这些方法和速记事件处理程序设置器映射到该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 );
},
Run Code Online (Sandbox Code Playgroud)
请参阅https://github.com/jquery/jquery/blob/1.7/src/event.js#L965.
ros*_*lan 12
on在自然界非常接近delegate.那么为什么不使用代表呢?这是因为on不是孤军奋战.有off解除事件并one创建一个仅执行一次的事件.这是一个新事件的"包".
主要问题live是它附加到"窗口",强制在页面结构(dom)内部的元素上发出单击事件(或其他事件),以"冒泡"到页面顶部以查找事件处理者愿意处理它.在每个级别,必须检查所有事件处理程序,如果你做深度重叠,这可以快速加起来(<body><div><div><div><div><table><table><tbody><tr><td><div><div><div><ul><li><button> etc etc etc...)
所以,bind像click,像其他的快捷键事件粘合剂直接连接到事件目标.如果你有一个表,比方说1000行和100列,每个100'000单元格都包含一个你想要处理的复选框.附加100'000事件处理程序将占用大量页面加载时间.在表级创建单个事件,并使用事件委托可以提高几个数量级的效率.将在事件执行时检索事件目标." this"将成为表格,但" event.target"将成为您通常的" this" click功能.现在好消息on是" this"将始终是事件目标,而不是它所附加的容器.
有.on方法,有可能做的.live,.delegate以及.bind具有相同的功能,但与.live()仅.live()是可能的(事件委托给文件).
jQuery("#example").bind( "click", fn ) = jQuery( "#example").on( "click", fn );
jQuery("#example").delegate( ".examples", "click", fn ) = jQuery( "#example" ).on( "click", ".examples", fn )
jQuery("#example").live( fn ) = jQuery( document ).on( "click", "#example", fn )
我可以直接从jQuery源确认这个:
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 );
},
Run Code Online (Sandbox Code Playgroud)
jQuery(this.context)?在大多数情况下this.context===document