How can I rebind .click() functions after .load()?

$('a').click(function() {
  _link = $(this).attr('href');
  loadContent(_link);
  return false;
});
function loadContent(href){
  $('#content').load(href + ' #content > *)
}

I have all <a> binded with a .click() that will only change the contents of #content. However, new <a> from the new #content arent working with the previous .click() function. How can I rebind it?

Adding the function again after the .load() seems to work

function loadContent(href){
  $('#content').load(href + ' #content > *);
  $('a').click(function() {
    _link = $(this).attr('href');
    loadContent(_link);
    return false;
  });
}

But would this mess up the `s’ that were already binded and cause it to run it on a loop?


solution

Use event delegation to bind events to dynamically added elements (in this case as):

$(document).on('click', 'a', function() {
  _link = $(this).attr('href');
  loadContent(_link);
  return false;
});

Event delegation works by listening for events bubbling up to a non-changing ancestor (document is the best default if none is handy, do not use 'body' as it has click bugs relating to styling). It then applies the jQuery selector to the elements in the bubble chain, it then applies your function to the matching element(s) that caused the event. The advantage is that the elements only need to exist at event time and now when the handler was registered.