February 2, 2010
One of the issues with live method is that live method first searches through all the elements then throws away the result.
$('p').live('click', function({})
In the above case jQuery does nothing with the selected p
elements. Since the
result does not really matter, it is a good idea to remove such codes from the
document ready
callbacks list.
So instead of doing this
$(function(){
$('p').live('click', function({})
})
just do this
$('p').live('click', function({})
John just landed this commit which adds delegate method .
Html markup
<div id="lab">
<p>p inside lab</p>
</div>
<p>p outside lab</p>
If you want to track all the clicks on p then you could write like this.
$(document).delegate("p", "click", function () {
log("p was clicked");
});
However if you only want to track clicks on 'p' which are inside the id lab
then you can write like this.
$("#lab").delegate("p", "click", function () {
log("p was clicked");
});
Note this functionality is in jQuery edge and is not available in jQuery 1.4.1. So you will have to get jQuery code from github to play with it.
If you are interested in the jQuery.live vs jQuery.fn.live discussion then follow this thread .
If this blog was helpful, check out our full blog archive.