.on()方法一种方式来调用它们。当然
.unbind() ,
.die() 和.
undelegate()方法也一样。一下代码片段是从Jquery 1.7版本的源码中截取出来的
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
return arguments.length == 1 ?
this.off( selector, "**" ) :
this.off( types, selector, fn );
}
考虑到这一点,使用
.on()方法看起来像以下方式一样…
/* Jquery的 .bind() , .live() 和 .delegate() 方法只需要使用`.on()`方法一种方式来调用它们 */// Bind
$( "#members li a" ).on( "click", function( e ) {} );
$( "#members li a" ).bind( "click", function( e ) {} );
// Live
$( document ).on( "click", "#members li a", function( e ) {} );
$( "#members li a" ).live( "click", function( e ) {} );
// Delegate
$( "#members" ).on( "click", "li a", function( e ) {} );
$( "#members" ).delegate( "li a", "click", function( e ) {} );
你可能注意到了,我如何使用
.on()方法决定了它如何调用其他方法。你可以认为
.on()方法被具有不同签名的方法”重载“了,而这些方法实现了不同的事件绑定的连接方式。
.on()方法的出现为API带来了很多方面的一致性,并希望让事情变得不那么混乱。优点:
使各种事件绑定方法一致。
因为在Jquery源码中
.bind() ,
.live() 和
.delegate()方法实际上是调用了此方法,因此简化了jQuery代码库并删除了一级重定向。这种方式仍然提供了使用
.delegate()方法的优点,并且仍然提供对
.bind()方法的支持,如果你需要的话。缺点:
给人带来了一些疑惑,因为方法的实际执行方式将根据你如何调用方法而改变。










