Here’s my function to load my content:
$("#site-nav .nav1").on('click', function () {
$(this).addClass("nav-active");
$('ul.top-level').load('assets/includes/recent.php', function () {
$(this).show();
});
event.preventDefault();
});
That content loads into ul.top-level fine.
Once that content is loaded, I attempt to apply a class to any of the hrefs in the newly-loaded content:
$("ul.top-level li a").on('click', function () {
alert("hi");
$(this).addClass("nav-active");
});
This does not work, nor does the alert message. Any ideas?
It would be worth noting where you apply the new
clickhandlers, because there’s a good chance that the dom isn’t ready when you’re trying to attach them. However, you could probably solve this by usinglive()instead.live()applies to all future matched selectors, so if you load ajax content it should attach the click handlers to them automatically.Edit: Since
live()is deprecated, you can rewrite live usingon()instead as such: