What's the difference between `on` and `live` or `bind`?

前端 未结 7 2086
迷失自我
迷失自我 2020-11-22 16:00

In jQuery v1.7 a new method, on was added. From the documentation:

‘The .on() method attaches event handlers to the currently se

7条回答
  •  半阙折子戏
    2020-11-22 16:26

    with .on method it is possible to do .live, .delegate, and .bind with the same function but with .live() only .live() is possible ( delegating events to document ).

    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 )

    I can confirm this directly from jQuery source:

    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 );
    },
    

    jQuery( this.context )? this.context === document in most cases

提交回复
热议问题