Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

jquery - .live() vs .bind()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...