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

前端 未结 7 2050
迷失自我
迷失自我 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:47

    There isn't one for the basic use case. These two lines are functionally the same

    $( '#element' ).bind( 'click', handler );
    $( '#element' ).on( 'click', handler );
    

    .on() can also do event delegation, and is preferred.

    .bind() is actually just an alias for .on() now. Here's the definition of the bind function in 1.7.1

    bind: function( types, data, fn ) {
    return this.on( types, null, data, fn );
    },
    

    The idea for adding .on() was to create a unified event API, rather than having multiple functions for binding event; .on() replaces .bind(), .live() and .delegate().

提交回复
热议问题