kulebyashik
kulebyashik

Reputation: 5619

JQuery AJAX load. div doesn't reload itself or parent div

I'm doing this:

$(function () {
      $("#but").click(function () {
                $('#bigHtml').load('@Url.Action("SecondPage")');
            }); 
});

<div id="bigHtml">
    <div id="but"></div>
</div>

But it doesn't work. Am I doing something illegal? (@Url.Action works properly)

Upvotes: 0

Views: 1077

Answers (1)

Felix Kling
Felix Kling

Reputation: 816272

In this case, use .live() (emphasize mine):

Attach a handler to the event for all elements which match the current selector, now and in the future.

$("#but").live('click', function () {
    $('#bigHtml').load('@Url.Action("SecondPage")');
}); 

In your code, you are attaching the event handler to the one #but instance that is currently in the page. When you reload the content, this instance is removed, also the event listeners. The #but element from the new content is a different instance.

You are not rebinding the event handler. When the JavaScript code is called, jQuery looks for an element #but and is done. It does not look again for that element after you injected new content. live() overcomes this problem by not attaching the event handler to the element but the the document root.

Upvotes: 3

Related Questions