The main difference is that live
will work also for the elements that will be created after the page has been loaded (i.e. by your javascript code), while bind
will only bind event handlers for currently existing items.
// BIND example
$('div').bind('mouseover', doSomething);
// this new div WILL NOT HAVE mouseover event handler registered
$('<div/>').appendTo('div:last');
// LIVE example
$('div').live('mouseover', doSomething);
// this new appended div WILL HAVE mouseover event handler registered
$('<div/>').appendTo('div:last');
Update:
jQuery 1.7 deprecated live()
method and 1.9 has removed it. If you want to achieve the same functionality with 1.9+ you need to use a new method on()
which has slightly different syntax as it's invoked on document object and the selector is passed as a parameter. Therefor the code from above converted to this new way of binding events will look like this:
// ON example
$(document).on('mouseover', 'div', doSomething);
// this new appended div WILL HAVE mouseover event handler registered
$('<div/>').appendTo('div:last');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…