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

前端 未结 7 2056
迷失自我
迷失自我 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条回答
  •  Happy的楠姐
    2020-11-22 16:41

    on() is an attempt to merge most of jQuery's event binding functions into one. This has the added bonus of tidying up the inefficiencies with live vs delegate. In future versions of jQuery, these methods will be removed and only on and one will be left.

    Examples:

    // Using live()
    $(".mySelector").live("click", fn);
    
    // Equivalent `on` (there isn't an exact equivalent, but with good reason)
    $(document).on("click", ".mySelector", fn);
    
    // Using bind()
    $(".mySelector").bind("click", fn);
    
    // Equivalent `on`
    $(".mySelector").on("click", fn);
    
    // Using delegate()
    $(document.body).delegate(".mySelector", "click", fn);
    
    // Equivalent `on`
    $(document.body).on("click", ".mySelector", fn);
    

    Internally, jQuery maps all these methods and shorthand event handler setters to the on() method, further indicating that you should ignore these methods from now on and just use 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 );
    },
    

    See https://github.com/jquery/jquery/blob/1.7/src/event.js#L965.

提交回复
热议问题