jQueryr .on方法解析

.On()

 其实.bind(), .live(), .delegate()都是通过.on()来实现的,.unbind(), .die(), .undelegate(),也是一样的都是通过.off()来实现的,这是1.8.2的源码:

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 ) {
        // ( namespace ) or ( selector, types [, fn] )
        return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
    },

看一下,我们用如何用.on()来改写前面通过 .bind(), .live(), .delegate()所注册的事件:

/* The jQuery .bind(), .live(), and .delegate() methods are just one 
   line pass throughs to the new jQuery 1.8.2 .on() method */

// 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 ) {} );

优点:

  • 提供了一种统一绑定事件的方法
  • 仍然提供了.delegate()的优点,当然如果需要你也可以直接用.bind()

缺点:

  • 也许会对你产生一些困扰,因为它隐藏了一前面我们所介绍的三种方法的细节。

结论:

  • 用.bind()的代价是非常大的,它会把相同的一个事件处理程序hook到所有匹配的DOM元素上
  • 不要再用.live()了,它已经不再被推荐了,而且还有许多问题
  • .delegate()会提供很好的方法来提高效率,同时我们可以添加一事件处理方法到动态添加的元素上。
  • 我们可以用.on()来代替上述的3种方法

摘自:http://www.cnblogs.com/moonreplace/archive/2012/10/09/2717136.html

cssfirefly http://cssfirefly.cnblogs.com
原文地址:https://www.cnblogs.com/cssfirefly/p/3953062.html