I append to div container some div’s :
$.ajax(
{
type: "GET",
url: "/LoadedData",
data: { "pageNumber": pageNumber },
success: function (result) {
$('.Container').append(result);
}
}
and when i try to click on new div i just can’t. I omit this by using
$('.Container').live('click', function () {
});
but can You tell my why I can’t do this without using live() ?
You’re binding your event handlers to elements that exist when the page loads.
Elements that are added later must be bound at that time.
The alternative is to utilize event delegation. jQuery has 2 delegation methods,
.live()and.delegate().What happens with those methods is that the handler is not bound to the elements in question, but rather bound to some container. When the click event bubbles up to the container, jQuery checks to see if the element clicked matches the selector you gave it, and if so, fires the handler.
Visualize it like this:
Binds like this:
But this:
Binds like this:
So if you add additional
.itemelements to the.Container, they will just work, because the handler processes all clicks inside.Container.So the click events on the new items bubble just like on the original ones.
The
.live()method works the same as the.delegate()method. It just uses thedocumentas the default container, which means that it has to process all clicks on the page.Because of this, I prefer
.delegate().